package com.huayi.datagovernance.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.text.StrBuilder;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huayi.datagovernance.common.SysConstant;
import com.huayi.datagovernance.dao.master.DeviceDao;
import com.huayi.datagovernance.dao.master.TYDao;
import com.huayi.datagovernance.dao.master.TopoDao;
import com.huayi.datagovernance.dto.Point;
import com.huayi.datagovernance.dto.ShapeDto;
import com.huayi.datagovernance.entity.*;
import com.huayi.datagovernance.exception.BizException;
import com.huayi.datagovernance.service.*;
import com.huayi.datagovernance.utils.Base64;
import com.huayi.datagovernance.utils.*;
import com.huayi.datagovernance.vo.ResponseResult;
import com.huayi.datagovernance.vo.WorkOrderPageVo;
import com.huayi.datagovernance.vo.XlListVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.axiom.om.OMElement;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * 设备模型服务-接口实现
 *
 * @version 1.0
 * @date 2021/4/21 15:36
 */
@Service
@Slf4j
public class DeviceServiceImpl implements DeviceService {

    @Value("${gis.TopoService.url}")
    private String topoService;

    @Resource
    private TYDao tyDao;

    @Resource
    private DeviceDao deviceDao;

    @Resource
    private ShapeUtil shapeUtil;

    @Resource
    private ConfModelmetaService modelmetaService;

    @Resource
    private TYwTaskService ywTaskService;

    @Resource
    private TYwTqlbService ywTqlbService;

    @Resource
    private TYwTaskYkService ywTaskYkService;

    @Resource
    private LxTaskService lxTaskService;

    @Resource
    private ConfToporelationXxVerService toporelationService;

    @Resource
    private TopoDao topoDao;

    @Resource
    private DataBrokerUtil dataBrokerUtil;

    @Resource
    private TZyRcvInfoService tZyRcvInfoService;

    @Override
    public ResponseResult<JSONObject> outPic(JSONObject jsonObject) {
        log.info("outPic参数：" + jsonObject.toJSONString());
        //1. 参数完整性校验
        String versionid = jsonObject.getString(SysConstant.FIELD_VERSIONID);
        String tqsbid = jsonObject.getString(SysConstant.FIELD_TQSBID);
        Integer gdtype = jsonObject.getInteger(SysConstant.FIELD_GDTYPE);
        if (StrUtil.isEmpty(versionid) || StrUtil.isEmpty(tqsbid)
                || gdtype == null) {
            return ResponseResult.failed(jsonObject, "设备信息缺失！（例如：tqsbid/versionid/gdtype）");
        }
        //2. 工单类型校验 (1,2,3,4)
        if (gdtype < 1 || gdtype > 4) {
            return ResponseResult.failed(jsonObject, "工单类型不存在");
        }

        //3. 判断已办还是待办出图
        String taskStatus = jsonObject.getString(SysConstant.TASK_STATUS);
        if (StrUtil.isEmpty(taskStatus)) {
            taskStatus = SysConstant.TASK_STATUS_NO;//不传默认为待办
        }
        List<JSONObject> dataResult = null;
        if (taskStatus.equals(SysConstant.TASK_STATUS_YES)) {
            dataResult = new ArrayList<>();
            //-----------------------本库资源---------------------
            List<JSONObject> outpicParams = tyDao.getTableList(gdtype);
            for (JSONObject param : outpicParams) {
                //modelName为空则跳过
                if (StrUtil.isEmpty(param.getString(SysConstant.FIELD_MODELNAME))) {
                    continue;
                }
                param.put(SysConstant.FIELD_VERSIONID, versionid);
                List<JSONObject> devices = this.getDeviceInfoList(param);
                devices.forEach(e -> e.put(SysConstant.FIELD_CLASSID, param.get(SysConstant.FIELD_CLASSID)));
               /* for (Map entity : devices) {
                    entity.put("classid", obj.get("classid"));
                }*/
                log.info("====查询表数据，{}，{}条====", param.getString(SysConstant.FIELD_MODELNAME), (devices == null ? 0 : devices.size()));
                if (devices != null && devices.size() > 0) {
                    dataResult.addAll(devices);
                }
            }
        } else {
            //----------------------台区资源------------------------
            JSONObject param = new JSONObject();
            param.put(SysConstant.FIELD_TQSBID, tqsbid);
            param.put(SysConstant.FIELD_GDTYPE, gdtype);
            dataResult = this.getDeviceTqList(param);
        }
//        dataResult=this.removeBaseDataWitchInVer(dataResult2,dataResult1,true); //合并基表和版本表的数据
        return this.formatOutPic(dataResult, gdtype);
    }

    @Override
    public List<JSONObject> getDeviceInfoList(JSONObject jsonObject) {
        try {
//            log.info("查找设备信息：" + jsonObject.toJSONString());
            String modelName = jsonObject.getString(SysConstant.FIELD_MODELNAME);
            Object classid = jsonObject.get(SysConstant.FIELD_CLASSID);//int8类型
            //1. 拼接表名 添加前缀
            String zyTableName = StrUtil.addPrefixIfNot(modelName, SysConstant.PREFIX_TABLE_ZY);
            String txTableName = StrUtil.addPrefixIfNot(modelName, SysConstant.PREFIX_TABLE_TX);
            //2. 查询版本表，添加后缀
            jsonObject.put(SysConstant.FIELD_ZY_TABLE, StrUtil.addSuffixIfNot(zyTableName, SysConstant.SUFFIX_TABLE_VER));
            jsonObject.put(SysConstant.FIELD_TX_TABLE, StrUtil.addSuffixIfNot(txTableName, SysConstant.SUFFIX_TABLE_VER));
            //3. 查询本地建模设备数据
            List<JSONObject> deviceMainList = deviceDao.getDeviceMainList(jsonObject);
            if (CollUtil.isNotEmpty(deviceMainList)) {
                //4. 偏移量
                List<Double> offset = shapeUtil.getOffSet();
                for (JSONObject device : deviceMainList) {
                    //添加classid
                    device.put(SysConstant.FIELD_CLASSID, classid);
                    //处理坐标
                    String shape = device.getString(SysConstant.FIELD_SHAPE);
                    if (StrUtil.isNotEmpty(shape)) {
                        ShapeDto shapeDto = shapeUtil.dealWithShape(shape, offset);
                        device.put(SysConstant.FIELD_POINTS, shapeDto.getPoints());
                        for (String type : SysConstant.SHAPE_TYPE.keySet()) {
                            if (StrUtil.equals(SysConstant.SHAPE_TYPE.get(type), shapeDto.getType())) {
                                device.put("geotype", type);
                                device.put("type", shapeDto.getType());
                            }
                        }
                    }
                    device.put("modelName", modelName);
                }
            }
//        log.info("返回设备:"+JSONObject.toJSONString(list));
            return deviceMainList;
        } catch (Exception e) {
            log.error("获取设备图形和资源信息失败", e);
            throw new BizException("获取设备图形和资源信息失败", e);
        }
    }

    @Override
    public List<JSONObject> getDeviceTqList(JSONObject jsonObject) {
        try {
            //验证工单类型：1-专线，2-台区, 3-业扩，4-高压核查
            String gdtype = jsonObject.getString(SysConstant.FIELD_GDTYPE);
            if (StrUtil.isEmpty(gdtype)) {
                log.warn("getDeviceTqList执行失败->工单类型不为空!");
                return null;
            }
            //默认是台区
            String tableName = SysConstant.TASK_STATE_TABLE.get(SysConstant.TASK_STATE_TQ);
            if (SysConstant.TASK_STATE_ZXS.contains(gdtype)) {
                tableName = SysConstant.TASK_STATE_TABLE.get(SysConstant.TASK_STATE_ZX);//专线
            }
            //设置查询表
            jsonObject.put("tableName", tableName);
            //查询下发的台区设备信息
            List<JSONObject> deviceTqList = deviceDao.getDeviceTqList(jsonObject);
            if (CollUtil.isNotEmpty(deviceTqList)) {
                List<Double> offset = shapeUtil.getOffSet();
                for (JSONObject device : deviceTqList) {
                    //处理shape 转 坐标
                    String shape = device.getString(SysConstant.FIELD_SHAPE);
                    if (StrUtil.isNotEmpty(shape)) {
                        ShapeDto shapeDto = shapeUtil.dealWithShape(shape, offset);
                        device.put(SysConstant.FIELD_POINTS, shapeDto.getPoints());
                        for (String type : SysConstant.SHAPE_TYPE.keySet()) {
                            if (StrUtil.equals(SysConstant.SHAPE_TYPE.get(type), shapeDto.getType())) {
                                device.put("geotype", type);
                                device.put("type", shapeDto.getType());
                            }
                        }
                    }
                }
            }
//        log.info("返回设备:"+JSONObject.toJSONString(list));
            return deviceTqList;
        } catch (Exception e) {
            log.error("获取下发台区数据失败", e);
            throw new BizException("获取下发台区数据失败", e);
        }
    }

    @Override
    public ResponseResult<JSONObject> formatOutPic(List<JSONObject> deviceList, int gdtype) {
        try {
//        log.info("formatOutPic格式化出图数据：{}", deviceList);
            String modelnamexl = SysConstant.MODELNAME_DY_XL;
            String modelnamewlg = SysConstant.MODELNAME_DY_WLGT;
            String tableName = SysConstant.TASK_STATE_TABLE.get(SysConstant.TASK_STATE_TQ);//台区

            if (SysConstant.TASK_STATE_ZXS.contains(String.valueOf(gdtype))) {
                modelnamexl = SysConstant.MODELNAME_XL;
                modelnamewlg = SysConstant.MODELNAME_WLGT;
                tableName = SysConstant.TASK_STATE_TABLE.get(SysConstant.TASK_STATE_ZX);
            }
            List<JSONObject> features = new ArrayList<>();
            for (JSONObject device : deviceList) {
                String shape = device.getString(SysConstant.FIELD_SHAPE);
                if (StrUtil.isEmpty(shape)) {
//                    log.info("设备[{}]坐标为空", device);
                    continue;
                }
                JSONObject feature = new JSONObject();
                JSONObject geometry = new JSONObject();
                String classid = device.getString("classid");
                if (SysConstant.blqClassids.contains(classid)) {
                    continue;
                }
                String type = SysConstant.SHAPE_POINT;
                if (shape.contains(SysConstant.SHAPE_LINESTRING)) {
                    type = SysConstant.SHAPE_LINESTRING;
                }
                if (shape.contains(SysConstant.SHAPE_POLYGON)) {
                    type = SysConstant.SHAPE_POLYGON;
                }
                JSONArray points = device.getJSONArray(SysConstant.FIELD_POINTS);
                List<Object> coordinates = new ArrayList<>();
                if (points != null) {
                    if (points.size() > 1) {
                        for (int j = 0; j < points.size(); j++) {
                            Point point = points.getObject(j, Point.class);
                            List<Object> str = new ArrayList<>();
                            str.add(point.getX());
                            str.add(point.getY());
                            coordinates.add(str);
                        }
                    } else {
                        Point point = points.getObject(0, Point.class);
                        coordinates.add(point.getX());
                        coordinates.add(point.getY());
                    }
                }
                geometry.put("coordinates", coordinates);
                geometry.put("type", type);

                JSONObject properties = new JSONObject();
                properties.put("sbmc", device.get("sbmc"));
                properties.put("sbzlx", device.get("sbzlx"));
                properties.put("zw_type", device.get("classid"));
                properties.put("typeName", device.get("modelalias"));
                properties.put("oid", device.get("oid"));
                properties.put("sbid", device.get("sbid"));
                properties.put("fhjd", device.get("fhjd"));
                properties.put("dydj", device.get("dydj"));
                //            properties.put("ssxl", device.get("ssxl"));
                properties.put("yxdw", device.get("yxdw"));

                //数据来源
                if (device.get("dataType") != null) {
                    properties.put("dataType", device.get("dataType"));
                }

                //台区数据端子号获取
                if (device.get("toponodeid") != null) {
                    String conn = device.get("toponodeid").toString().replaceAll(",", "|");
                    properties.put("conn", conn);
                }
                //起始电站
                if (device.get("qsdz") != null) {
                    properties.put("qsdz", device.get("qsdz"));
                }

                if (device.get("ssjg") != null && StrUtil.isNotEmpty(device.getString("ssjg"))) {
                    properties.put("ssjg", device.get("ssjg"));
                }
                //查询资源表中 ssxl或者sswlg的名称
                String ssxl = device.getString("ssxl");
                String sswlg = device.getString("sswlg");
                JSONObject xlIfno = null;
                JSONObject wlgInfo = null;
                if (StrUtil.isNotEmpty(ssxl)) {
                    properties.put("ssxl", device.get("ssxl"));
                    xlIfno = deviceDao.getSbmcByModelnameAndOid(StrUtil.strBuilder(SysConstant.PREFIX_TABLE_ZY, modelnamexl, SysConstant.SUFFIX_TABLE_VER).toString()
                            , Long.valueOf(ssxl));
                    if (xlIfno == null) { //本地建模查不到，到下发的数据中找
                        List<JSONObject> xlIfnos = deviceDao.getSbmcByTableAndOidFromIssue(tableName, Long.valueOf(ssxl));
                        if (CollUtil.isNotEmpty(xlIfnos)) {
                            xlIfno = xlIfnos.get(0);
                        }
                    }
                    if (xlIfno != null) {//不为空就赋值
                        properties.put("ssxlName", StrUtil.emptyToDefault(xlIfno.getString("sbmc"), ""));
                    } else {
                        properties.put("ssxlName", "");
                    }
                }
                if (StrUtil.isNotEmpty(sswlg)) {
                    properties.put("sswlg", device.get("sswlg"));
                    wlgInfo = deviceDao.getSbmcByModelnameAndOid(StrUtil.strBuilder(SysConstant.PREFIX_TABLE_ZY, modelnamewlg, SysConstant.SUFFIX_TABLE_VER).toString()
                            , Long.valueOf(sswlg));
                    if (wlgInfo == null) {//本地建模查不到，到下发的数据中找
                        List<JSONObject> wlgInfos = deviceDao.getSbmcByTableAndOidFromIssue(tableName, Long.valueOf(sswlg));
                        if (CollUtil.isNotEmpty(wlgInfos)) {
                            wlgInfo = wlgInfos.get(0);
                        }
                    }
                    if (wlgInfo != null) {//不为空就赋值
                        properties.put("sswlgName", StrUtil.emptyToDefault(wlgInfo.getString("sbmc"), ""));
                    } else {
                        properties.put("sswlgName", "");
                    }

                }

                feature.put("type", "Feature");
                feature.put("geometry", geometry);
                feature.put("properties", properties);
                features.add(feature);

            }
            JSONObject geoJson = new JSONObject();
            geoJson.put("features", features);
            geoJson.put("type", "FeatureCollection");
            log.info("geoJson格式返回信息：{}", geoJson);
            return ResponseResult.success(geoJson);
        } catch (Exception e) {
            log.error("格式化出图数据失败", e);
            throw new BizException("格式化出图数据失败", e);
        }
    }

    @Override
    public ResponseResult<IPage<WorkOrderPageVo>> getWorkOrderPage(JSONObject jsonObject) {
        try {
            log.info("getMessageList参数：" + jsonObject.toJSONString());
            //{"searchname":"","currPage":1,"orgNo":"1440112","pageSize":10,"isdone":0,"gdtype":"4","userid":"7A5BD7FE69BA4FE8A4D0CD1202DA05FA"}
            // 1. 参数判断，拼接条件
            JSONObject param = new JSONObject();
            // 是否完成
            Integer isdone = jsonObject.getInteger(SysConstant.FIELD_IS_DONE);
            if (isdone != null) {
                param.put(SysConstant.FIELD_IS_DONE, isdone);//设置条件
                //已办 :sfts in (2,3) and isdone=1 | 待办 : sfts in (1) and isdone=0
                if (isdone == SysConstant.IS_DONE_TRUE) {//已办
                    log.info("------查询已办------");
                    param.put("sftsList", ListUtil.list(false, 2, 3));
                }
                if (isdone == SysConstant.IS_DONE_FALSE) {//待办
                    log.info("------查询待办------");
                    param.put("sftsList", ListUtil.list(false, 1));
                }
            }
            // 工单名称关键字
            String searchname = jsonObject.getString(SysConstant.FIELD_SEARCH_NAME);
            if (StrUtil.isNotBlank(searchname)) {
                param.put(SysConstant.FIELD_SEARCH_NAME, searchname);
            }
            // 版本号
            String versionid = jsonObject.getString(SysConstant.FIELD_VERSIONID);
            if (StrUtil.isNotBlank(versionid)) {
                param.put(SysConstant.FIELD_VERSIONID, versionid);
            }
            //工单类型：1-专线，2-台区, 3-业扩，4-高压核查
            String gdtype = jsonObject.getString(SysConstant.FIELD_GDTYPE);
            if (StrUtil.isNotBlank(gdtype)) {
                param.put(SysConstant.FIELD_GDTYPE, Integer.valueOf(gdtype));
                //用户id 专线台区
                if (gdtype.equals(SysConstant.TASK_STATE_TQ) || gdtype.equals(SysConstant.TASK_STATE_ZX)) {
                    String userid = jsonObject.getString(SysConstant.FIELD_USER_ID);
                    if (StrUtil.isNotEmpty(userid)) {
                        param.put(SysConstant.FIELD_USER_ID, userid);
                    }
                }
                //单位编号
                if (gdtype.equals(SysConstant.TASK_STATE_HIGH_CHECK)) {
                    String orgNo = param.getString(SysConstant.FIELD_ORG_NO);
                    if (StrUtil.isNotEmpty(orgNo)) {
                        param.put(SysConstant.FIELD_ORG_NO, orgNo.substring(0, 7));
                    }
                }
            }

            // 获取分页参数
            int currPage = jsonObject.getInteger(SysConstant.FIELD_CURR_PAGE) == null ? 1 : jsonObject.getInteger(SysConstant.FIELD_CURR_PAGE);
            int pageSize = jsonObject.getInteger(SysConstant.FIELD_PAGE_SIZE) == null ? 10 : jsonObject.getInteger(SysConstant.FIELD_PAGE_SIZE);
            param.put(SysConstant.FIELD_CURR_PAGE, currPage);
            param.put(SysConstant.FIELD_PAGE_SIZE, pageSize);
            //查库
            List<WorkOrderPageVo> records = deviceDao.getWorkOrderPage(param);
            IPage<WorkOrderPageVo> page = new Page<>(currPage, pageSize);
            page.setRecords(records);
            page.setTotal(records.size());
            log.info("getMessageList最终返回：{}", JSONObject.toJSONString(page));
            return ResponseResult.success(page);
        } catch (NumberFormatException e) {
            log.error("查询工单任务列表失败，数值转换异常", e);
            throw new BizException("数值转换异常", e);
        } catch (Exception e) {
            log.error("查询工单任务列表失败", e);
            throw new BizException("查询工单任务列表失败", e);
        }
    }

    @Override
    public ResponseResult<JSONObject> getDeviceInfo(JSONObject jsonObject) {
        try {
            log.info("getDeviceInfo参数：{}", jsonObject);
            String sbzlx = jsonObject.getString(SysConstant.FIELD_MODELID);
            String versionid = jsonObject.getString(SysConstant.FIELD_VERSIONID);
            String oid = jsonObject.getString(SysConstant.FIELD_OID);
            String sbid = jsonObject.getString(SysConstant.FIELD_SBID);
            String gdtype = jsonObject.getString(SysConstant.FIELD_GDTYPE);
            // 1、参数校验
            if (StrUtil.isBlank(sbzlx)) {
                return ResponseResult.failed(jsonObject, "设备子类型不能为空");
            }
            if (StrUtil.isBlank(sbid)) {
                return ResponseResult.failed(jsonObject, "设备ID不能为空");
            }
            // 2. 根据设备子类型查表名
            QueryWrapper<ConfModelmeta> wrapper = new QueryWrapper<>();
            wrapper.eq(SysConstant.FIELD_MODELID, Long.valueOf(sbzlx));
            ConfModelmeta modelmeta = modelmetaService.getOne(wrapper);
            if (modelmeta == null || StrUtil.isBlank(modelmeta.getModelname())) {
                return ResponseResult.failed(jsonObject, "设备子类型不存在");
            }
            String modelname = modelmeta.getModelname();
            JSONObject device = null;
            JSONObject param;
            if (StrUtil.isNotBlank(versionid)) {
                //查询资源表，暂不查询图形表（没有fhjd、shape、txid信息）
                String zyTableName = StrUtil.builder(SysConstant.PREFIX_TABLE_ZY, modelname, SysConstant.SUFFIX_TABLE_VER).toString();
                String txTableName = StrUtil.builder(SysConstant.PREFIX_TABLE_TX, modelname, SysConstant.SUFFIX_TABLE_VER).toString();
                //构建参数
                param = new JSONObject();
                param.put(SysConstant.FIELD_ZY_TABLE, zyTableName);
                param.put(SysConstant.FIELD_TX_TABLE, txTableName);
                param.put(SysConstant.FIELD_VERSIONID, Long.valueOf(versionid));
                param.put(SysConstant.FIELD_SBID, sbid);
                //查询新建设备
                device = deviceDao.getDeviceMainOne(param);
            }
            if (device == null && StrUtil.isNotBlank(gdtype)) {//工单类型不为空，且新建设备查无数据
                //表名 默认是台区
                String tableName = SysConstant.TASK_STATE_TABLE.get(SysConstant.TASK_STATE_TQ);
                if (SysConstant.TASK_STATE_ZXS.contains(gdtype)) {
                    tableName = SysConstant.TASK_STATE_TABLE.get(SysConstant.TASK_STATE_ZX);//专线
                }
                //构建参数
                param = new JSONObject();
                param.put("tableName", tableName);
                param.put(SysConstant.FIELD_VERSIONID, versionid);
                param.put(SysConstant.FIELD_SBZLX, Long.valueOf(sbzlx));
                param.put(SysConstant.FIELD_SBID, sbid);
                if (StrUtil.isNotBlank(oid)) {
                    param.put(SysConstant.FIELD_SBOID, Long.valueOf(oid));
                }
                //查询下发设备
                device = deviceDao.getDeviceTqOne(param);
            }
            log.info("getDeviceInfo最终返回：{}", device);
            return ResponseResult.success(device);
        } catch (Exception e) {
            log.error("查询设备详情失败", e);
            throw new BizException("查询设备详情失败", e);
        }
    }

    @Override
    public ResponseResult<Object> getXlList(JSONObject jsonObject) {
        try {
            log.info("getXlList参数：{}", jsonObject);
            //1. 设置参数
            String gdtype = jsonObject.getString(SysConstant.FIELD_GDTYPE);
            if (StrUtil.isBlank(gdtype)) {
                return ResponseResult.failed(jsonObject, "工单类型不能为空");
            }
            String zyTableName, tableName;
            List<Integer> sbzlxs;
            if (SysConstant.TASK_STATE_ZXS.contains(gdtype)) { //专线、业扩、高压
                zyTableName = "t_zy_zwyc_xl_ver";
                tableName = "t_yw_zxdata";
                sbzlxs = ListUtil.list(false, 10000000, 10000001);
            } else { //台区
                zyTableName = "t_zy_dysb_dyxl_ver";
                tableName = "t_yw_tqzxdata";
                sbzlxs = ListUtil.list(false, 310000000);
            }
            //2. 查询
            List<XlListVo> xlListVos = ListUtil.list(false);
            String versionid = jsonObject.getString(SysConstant.FIELD_VERSIONID);
            String tqsbid = jsonObject.getString(SysConstant.FIELD_SBID);
            if (StrUtil.isNotBlank(versionid)) {//版本号不为空查询新建线路
                //---------------------本库找线路信息--------------------
                JSONObject param = new JSONObject();
                param.put("tableName", zyTableName);
                param.put(SysConstant.FIELD_VERSIONID, Long.valueOf(versionid));
                param.put(SysConstant.FIELD_SBZLX, sbzlxs);
                List<XlListVo> newXlList = deviceDao.getXlList(param);//新建线路
                if (CollUtil.isNotEmpty(newXlList)) {
                    xlListVos.addAll(newXlList);
                }
            }
            if (StrUtil.isNotBlank(tqsbid)) {//查询专线表
                //---------------------台区资源找--------------
                JSONObject tqParam = new JSONObject();
                tqParam.put("tableName", tableName);
                tqParam.put(SysConstant.FIELD_TQSBID, tqsbid);
                tqParam.put(SysConstant.FIELD_SBZLX, sbzlxs);
                List<XlListVo> tqXlList = deviceDao.getXlList(tqParam);//新建线路
                if (CollUtil.isNotEmpty(tqXlList)) {
                    xlListVos.addAll(tqXlList);
                }
            }
            log.info("最终返回：{}", xlListVos);
            return ResponseResult.success(xlListVos.size() == 0 ? null : xlListVos);
        } catch (Exception e) {
            log.error("获取线路列表失败", e);
            throw new BizException("获取线路列表失败", e);
        }
    }

    @Override
    public ResponseResult<TYwTask> commitTask(JSONObject jsonObject) {
        try {
            log.info("commitTask参数：{}", jsonObject);
            String versionid = jsonObject.getString(SysConstant.FIELD_VERSIONID);
            if (StrUtil.isBlank(versionid)) {
                throw new BizException("版本号ID不能为空");
            }
            String gdtype = jsonObject.getString(SysConstant.FIELD_GDTYPE);
            if (StrUtil.isEmpty(gdtype)) {
                throw new BizException("工单类型不能为空");
            }
            JSONArray byqArr = jsonObject.getJSONArray("byqList");
            List<TYwTaskYk> byqList = null;
            if (!byqArr.isEmpty()) {
                byqList = byqArr.toJavaList(TYwTaskYk.class);
            }
            //查询工单信息，根据versionid
            QueryWrapper<TYwTask> wrapper = new QueryWrapper<>();
            wrapper.eq(SysConstant.FIELD_VERSIONID, Integer.valueOf(versionid));
            List<TYwTask> list = ywTaskService.list(wrapper);
            if (CollUtil.isEmpty(list)) {
                throw new BizException("根据版本号查无工单信息!");
            }
            if (list.size() > 1) {
                throw new BizException("存在多条版本号相同的数据!");
            }
            TYwTask ywTask = list.get(0);
            //修改任务为已处理
            UpdateWrapper<TYwTqlb> wrapperTqlb = new UpdateWrapper<>();
            wrapperTqlb.set(SysConstant.FIELD_IS_DONE, SysConstant.IS_DONE_TRUE);
            wrapperTqlb.eq("taskid", ywTask.getOid());
            ywTqlbService.update(wrapperTqlb);
            //任务推送到web
            ywTask.setSfts(SysConstant.SFTS_PUSH_WEB);//推送到web
            ywTask.setTasktime(DateTime.now());//更新 当前时间
            ywTask.setResolveType(SysConstant.RESOLVE_TYPE_APP);//标记 APP端处理
            ywTaskService.updateById(ywTask);
            //低压台区，回写表箱采集信息到智越
            if (gdtype.equals(SysConstant.TASK_STATE_TQ)){
                log.info("=======回写低压表箱采集信息=======");
                List<TZyRcvInfo> bxList = jsonObject.getJSONArray("bxList").toJavaList(TZyRcvInfo.class);
                tZyRcvInfoService.saveJlxCollectInfoBatch(bxList);
            }
            //更新业扩工单状态，变压器信息（经纬度）
            if (gdtype.equals(SysConstant.TASK_STATE_YK)) {
                log.info("=======提交业扩任务=======");
                if (byqList != null) {
                    //回写本地变压器
                    ywTaskYkService.saveBatch(byqList);
                    //回写朗新变压器
                    lxTaskService.updateYkByqInfo(byqList);
                }
            }
            //高压核查，更新工单状态
            if (gdtype.equals(SysConstant.TASK_STATE_HIGH_CHECK)) {
                log.info("=======提交高压核查任务=======");
//                String taskId = jsonObject.getString("taskid");//工单号
                String taskId = ywTask.getTaskid();//工单号
                if (StrUtil.isEmpty(taskId)) {
                    throw new BizException("高压核查工单号不能为空!");
                }
//                JSONArray array = jsonObject.getJSONArray("byqList");
//                if (array == null) {
//                    throw new BizException("高压核查变压器采集信息不能为空!");
//                }
                if (byqList != null) {
//                    throw new BizException("高压核查变压器采集信息不能为空!");
                    //修改本地工单状态，和变压信息
                    ywTaskYkService.updateHighCheckStatusAndByq(SysConstant.HIGH_CHECK_STATE_SUCCESS, byqList);
                    //修改朗新工单状态，和变压信息
                    lxTaskService.updateHighCheckStatus(taskId, SysConstant.HIGH_CHECK_STATE_SUCCESS, byqList);
                }

            }
            ResponseResult<TYwTask> result = ResponseResult.success(ywTask);
            log.info("commitTask提交成功:{}", result);
            return result;
        } catch (Exception e) {
            log.error("commitTask执行失败", e);
            throw new BizException("保存工单任务失败");
        }
    }

    @Override
    public ResponseResult sendToGis(JSONObject jsonObject) {
        String gdtype = jsonObject.getString(SysConstant.FIELD_GDTYPE);
        String taskid = jsonObject.getString("taskid");
        String resultStr = "";//返回内容
        if (SysConstant.TASK_STATE_ZXS.contains(gdtype)) {
            //成功的时候往数据代理插入数据
            Map<String, Object> paramHttp = new HashMap<>();
            paramHttp.put(SysConstant.FIELD_OID, taskid);
            paramHttp.put(SysConstant.FIELD_VERSIONID, jsonObject.get(SysConstant.FIELD_VERSIONID));
            log.info("数据开始回写GIS：[url=" + SysConstant.SEND_DATA_2_GIS_URL + ",param=" + JSONObject.toJSONString(paramHttp) + "]");
            resultStr = HttpUtil.sendPost(SysConstant.SEND_DATA_2_GIS_URL, JSONObject.toJSONString(paramHttp));
            log.info("数据回写gis结果: {}", resultStr);
//                if(StrUtil.isEmpty(resultStr)){
//                    throw new BizException("数据回写gis失败！请核实！"+SysConstant.SEND_DATA_2_GIS_URL);
//                }
              /*  JSONObject httpStr=JSONObject.parseObject(resultStr);
                if(!(boolean)httpStr.get("success")){
                    result=new ResponseResult(false,"数据回写gis返回结果："+resultStr,list.get(0));
                }else {
                    result=new ResponseResult(true,"数据回写gis返回结果："+resultStr,list.get(0));
                }*/
        }
        return new ResponseResult(true, "gis回写结果: " + resultStr, null);
    }

    @Override
    public ResponseResult autoCreateModel3(JSONObject object) {
        try {
            if (object.get("modeldatas") == null) {
                throw new BizException("保存的设备数据不能为空");
            }
            //1 解码 base64 入参
            String modeldatas = object.getString("modeldatas");
            String jsonStr = new String(Base64.decode(modeldatas), StandardCharsets.UTF_8);
            log.info("autoCreateModel3原始参数：{}", jsonStr);
            JSONArray jsonArray = JSON.parseArray(jsonStr);
            /*
             * 构建集合请求gis获取sb主键->
             * 对象{modelName:"dysb_dywlg", "txTableName": "T_TX_DYSB_DYWLG",
             *  oid:"o123", con0:"n123", con1:"n234",
             *  newoid:"111", newcon0:"333", newcon1:"444"}
             */
            List<JSONObject> newSerialReqParams = new ArrayList<>();
            List<JSONObject> sqlResult = new ArrayList<>();//存储执行插入的 sql
            List<Double> offset = shapeUtil.getOffSet();//偏移量
            List<String> dealByqZyList = new ArrayList<>();//保存已经处理过资源表的变压器sbid，去重，每次判断，如果是该集合内的变压器，表示已经保存，不再进行处理
            List<String> dealByqTzList = new ArrayList<>();//保存已经处理过台账表的变压器sbid，去重，每次判断，如果是该集合内的变压器，表示已经保存，不再进行处理
            //2 遍历 转成可执行sql
            for (int i = 0; i < jsonArray.size(); i++) {
                int modelType = SysConstant.MODEL_ZY; //默认处理资源表
                //获取一条设备记录
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                //参数校验
                //1、判断设备子类型是否为空
                String currSbzlx = jsonObject.getString(SysConstant.FIELD_SBZLX);//当前设备子类型
                String currSbmc = jsonObject.getString("sbmc");//当前设备名称
                if (StrUtil.isEmpty(currSbzlx)) {
                    throw new BizException("设备[" + currSbmc + "]：缺失sbzlx字段");
                }
                //2、判断数据的归属 根据字段( sbid:资源表 ， obj_id：台账表  )
                if (StrUtil.isNotEmpty(jsonObject.getString(SysConstant.FIELD_SBID))) {
                    //资源表 数据
                    if (StrUtil.isEmpty(jsonObject.getString("apptype"))) {
                        throw new BizException("设备[" + currSbmc + "]：缺失apptype字段");
                    }
                    jsonObject.put(SysConstant.MODEL_TYPE, SysConstant.MODEL_ZY);
                } else if (StrUtil.isNotEmpty(jsonObject.getString(SysConstant.FIELD_OBJ_ID))) {
                    //台账表 数据
                    jsonObject.put(SysConstant.MODEL_TYPE, SysConstant.MODEL_TZ);
                    modelType = SysConstant.MODEL_TZ;
                } else {
                    //两个字段都不存在
                    throw new BizException("设备[" + currSbmc + "]：缺失sbid、obj_id字段");
                }

                //3、查询当前设备模型数据
//                String sbzlx =jsonObject.getString("sbzlx");
                Map<String, Object> modelmeta = tyDao.getModelNameByType(null, currSbzlx);
                if (modelmeta == null) {
                    throw new BizException("根据设备子类型找不到该类设备！");
                }
                String modelName = MapUtil.getStr(modelmeta, SysConstant.FIELD_MODELNAME);
                if (StrUtil.isEmpty(modelName)) {
                    throw new BizException("设备子类型[" + currSbzlx + "]模型：缺失modelname字段");
                }

                //4、构建序列号请求参数对象
                JSONObject serialReqParam = new JSONObject();
                //封装gisId请求参数
                serialReqParam.put("modelName", modelName);//放入modelName

                jsonObject.put("classid", modelmeta.get("classid"));
                String geotype = MapUtil.getStr(modelmeta, "geotype");
                jsonObject.put("geotype", shapeUtil.geoTypeToFourFigure(geotype));//geotype 转换成  2001、2002、2003

                String currSbid;//当前设备id
                String classid = MapUtil.getStr(modelmeta, "classid", "");
                if (modelType == SysConstant.MODEL_ZY) {
                    //资源表
                    currSbid = jsonObject.getString(SysConstant.FIELD_SBID);
                    //变压器去重处理
                    if ("110000".equals(classid) || "302000".equals(classid)) {
                        //判断处理过的变压器列表中，是否已经包含当前设备
                        if (dealByqZyList.contains(currSbid)) {
                            //存在，跳过本次循环
                            continue;
                        } else {
                            //放入当前变压器sbid
                            dealByqZyList.add(currSbid);
                        }
                    }
                } else {
                    //台账表
                    currSbid = jsonObject.getString(SysConstant.FIELD_OBJ_ID);
                    //变压器去重处理
                    if ("110000".equals(classid) || "302000".equals(classid)) {
                        //判断处理过的变压器列表中，是否已经包含当前设备
                        if (dealByqTzList.contains(currSbid)) {
                            //存在，跳过本次循环
                            continue;
                        } else {
                            //放入当前变压器sbid
                            dealByqTzList.add(currSbid);
                        }
                    }
                }

                //5、处理公共参数部分
                //1. 拼接表名 添加前缀
                String zyTableName = StrUtil.addPrefixIfNot(modelName, SysConstant.PREFIX_TABLE_ZY);//资源基表名
                String txTableName = StrUtil.addPrefixIfNot(modelName, SysConstant.PREFIX_TABLE_TX);//图形基表名
                serialReqParam.put(SysConstant.FIELD_TX_TABLE, txTableName.toUpperCase());//放入txTableName
                jsonObject.put(SysConstant.FIELD_TX_TABLE, txTableName);
                jsonObject.put(SysConstant.FIELD_ZY_TABLE, zyTableName);
                //6、部分传入字段的处理
                if (StrUtil.isNotEmpty(jsonObject.getString("taskId"))) {
                    jsonObject.put("versionid", jsonObject.get("taskId"));//任务id
                }
                if (StrUtil.isNotEmpty(jsonObject.getString("versionid"))) {
                    jsonObject.put("taskId", jsonObject.get("versionid"));//任务id
                }

                //7.1、判断资源数据是否已存在
                boolean existZy = false;
                List<JSONObject> zyList = this.getDeviceList2(jsonObject);
                if (zyList != null && zyList.size() > 1) {
                    existZy = true;
                }
                //7.2、判断台账数据是否已存在
                boolean existTz = false;
                String sbTableName = tyDao.getTableNameByModelName(txTableName.toUpperCase());//大写查找
                JSONObject tzData = null;
                if (StrUtil.isEmpty(sbTableName)) {
                    log.info("-----------------{}无台账表------------", txTableName);
                } else {
                    tzData = tyDao.getTzData(sbTableName, currSbid);
                    if (tzData != null && StrUtil.isNotEmpty(tzData.getString(SysConstant.FIELD_OBJ_ID))) {
                        existTz = true;
                    }
                }
                jsonObject.put("addflag", SysConstant.operate_add);//新增操作
                //如果当前为资源表的数据，直接判断如果存在就终止，台账则跳过
                if (modelType == SysConstant.MODEL_ZY) {
                    //处理资源
                    if (existZy) {
                        throw new BizException("sbid为[" + currSbid + "]的设备已存在图形数据,请不要重复新增!");
                    }
                    //添加资源+图形（1.都没有 2.有台账，无资源）
                    // 8.1、新建资源sql
                    sqlResult.add(this.getInsertDeviceSql2(jsonObject, zyTableName.toLowerCase(), offset));
                    Object oid = jsonObject.get("oid");
                    serialReqParam.put("oid", oid);//放入oid
                    newSerialReqParams.add(serialReqParam);//serialReqParam加入集合
                    // 8.2、新建图形
                    jsonObject.put("zyid", oid);
                    sqlResult.add(this.getInsertDeviceSql2(jsonObject, txTableName.toLowerCase(), offset));
                    //6.3、处理台账（1.没有不处理 2.有台账，建立关联）
//                    if (existTz){
//                    }
                } else {
                    //处理台账
                    if (existTz) {
                        throw new BizException("sbid为[" + currSbid + "]的设备已存在台账数据,请不要重复新增!");
                    }
                    //添加台账（1.都没有 2.有资源，无台账）
                    //特殊字段处理
                    if (StrUtil.isNotEmpty(sbTableName)) {
                        specialFieldValidation(jsonObject);
                        ResponseResult resultTz = this.insertDevice2(jsonObject, sbTableName.toLowerCase(), offset);
                        if (!resultTz.isSuccess()) {
                            throw new Exception(resultTz.getMsg());
                        }
                    }
                }

                //9 维护拓扑
//                List<String> connection1 =new ArrayList<>();
                String[] cons = null;
                if (jsonObject.get("connection") != null) {//端子号
                    String conStr = jsonObject.getString("connection");
                    if (StrUtil.isNotEmpty(conStr)) {
                        if (conStr.startsWith("[") && conStr.endsWith("]")) {
                            conStr = conStr.substring(1, conStr.length() - 1);
                            cons = conStr.split(",");
                            for (int j = 0; j < cons.length; j++) {
                                serialReqParam.put("con" + j, cons[j]);//放入conj
                            }
                        }
                    }
                } else {
//                    log.info("=============保存端子号conNO==================");
                    //点-端子
                    if (StrUtil.isNotEmpty(jsonObject.getString("conNO"))) {
                        cons = new String[]{jsonObject.getString("conNO")};
                        jsonObject.put("connection", "111");
                        serialReqParam.put("con0", jsonObject.getString("conNO"));//放入conj
                    }

                    //线-端子
                    if (StrUtil.isNotEmpty(jsonObject.getString("qdConNO")) && StrUtil.isNotEmpty(jsonObject.getString("zdConNO"))) {
                        cons = new String[]{jsonObject.getString("qdConNO"), jsonObject.getString("zdConNO")};
                        jsonObject.put("connection", "111");
                        serialReqParam.put("con0", jsonObject.getString("qdConNO"));//放入conj
                        serialReqParam.put("con1", jsonObject.getString("zdConNO"));//放入conj
                    }
                }
                if (cons != null && cons.length > 0) {
                    String taskId = jsonObject.getString("taskId");
                    int te = topoDao.getMaxTerminalByVersionid(taskId);
                    sqlResult.add(this.insertTopoSql(jsonObject, te + i, cons));
                }
            }
            //10 请求序列号
            for (JSONObject srp : newSerialReqParams) {
                //获取图形oid-》dataBrokerUtil.getOid((txTableName).toUpperCase()); 返回String-》newOid
//                srp.put("newoid", dataBrokerUtil.getOid(srp.getString("txTableName")));//放入新的oid
                srp.put("newoid", "001" + new Random().nextInt(50000));//放入新的oid
                //获取con 次数 有逗号两次， ->dataBrokerUtil.getOid(SysConstant.GIS_CONF_TOPORELATION); 返回String-》newCon
                if (srp.containsKey("con0")) {
//                    srp.put("newcon0", dataBrokerUtil.getOid(SysConstant.GIS_CONF_TOPORELATION)); //放入新的端子号，必须数量为2
                    srp.put("newcon0", "002" + new Random().nextInt(50000)); //放入新的端子号，必须数量为2
                }
                if (srp.containsKey("con1")) {
//                    srp.put("newcon1", dataBrokerUtil.getOid(SysConstant.GIS_CONF_TOPORELATION)); //放入新的端子号，必须数量为2
                    srp.put("newcon1", "003" + new Random().nextInt(50000)); //放入新的端子号，必须数量为2
                }
            }
            //11 拼接fieldValue
            StringBuilder fieldValueTotal = new StringBuilder();
            for (JSONObject sql : sqlResult) {
                fieldValueTotal.append(sql.getString("fieldValue")).append(";");
            }
            log.info("替换序列集合： {}", JSON.toJSONString(newSerialReqParams));
            //12 替换
            String valueSql = fieldValueTotal.toString();
            for (JSONObject srp : newSerialReqParams) {
                valueSql = valueSql.replace(srp.getString("oid"), srp.getString("newoid"));//替换oid
                if (srp.containsKey("newcon0")) {
                    valueSql = valueSql.replace(srp.getString("con0"), srp.getString("newcon0"));//端子号1
                }
                if (srp.containsKey("newcon1")) {
                    valueSql = valueSql.replace(srp.getString("con1"), srp.getString("newcon1"));//端子号2
                }
            }
            //13 分解;
            String[] values = valueSql.split(";");
            if (values.length == sqlResult.size()) {
                log.info("替换前执行建模SQL： {}", JSON.toJSONString(sqlResult));
                for (int i = 0; i < sqlResult.size(); i++) {
                    JSONObject sql = sqlResult.get(i);
                    sql.put("fieldValue", values[i]);
                    //14 保存图形和资源
                    deviceDao.insertDeviceModel2(sql);
                }
                log.info("最终执行建模SQL： {}", JSON.toJSONString(sqlResult));
            } else {
                throw new BizException("序列号替换失败");
            }

        } catch (Exception e) {
            log.error("autoCreateModel3执行异常，数据回滚", e);
            throw new BizException("批量建模失败: " + e.getMessage());
        }
        log.info("autoCreateModel3最终成功");
        return new ResponseResult(true, "建模成功", null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult autoCreateModel2(JSONObject object) {
        if (object.get("modeldatas") == null) {
            throw new BizException("autoCreateModel2参数不能为空");
        }
        String modeldatas = object.getString("modeldatas");
//        byte[] bytes = Base64.decode(modeldatas);
//        String jsonStr = new String(bytes, StandardCharsets.UTF_8);
        log.info("autoCreateModel2原始参数：{}", modeldatas);
        JSONArray jsonArray = JSON.parseArray(modeldatas);
//      JSONArray jsonArray = object.getJSONArray("modeldatas");

//        log.info("autoCreateModel2原始参数："+jsonArray.toJSONString());

        ResponseResult result = null;//返回
        try {
            List<Double> offset = shapeUtil.getOffSet();//偏移量
            for (int i = 0; i < jsonArray.size(); i++) {
                int model_type = SysConstant.MODEL_ZY; //默认处理资源表
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                //1、判断设备子类型是否为空
                String sbzlx = jsonObject.getString(SysConstant.FIELD_SBZLX);
                if (StrUtil.isEmpty(sbzlx)) {
                    throw new BizException("设备[" + jsonObject.getString("sbmc") + "]：缺失sbzlx字段");
                }
                //2、判断数据的归属 根据字段( sbid:资源表 ， obj_id：台账表  )
                if (StrUtil.isNotEmpty(jsonObject.getString(SysConstant.FIELD_SBID))) {
                    //资源表 数据
                    if (StrUtil.isEmpty(jsonObject.getString("apptype"))) {
                        throw new BizException("设备[" + jsonObject.getString("sbmc") + "]：缺失apptype字段");
                    }
                    jsonObject.put(SysConstant.MODEL_TYPE, SysConstant.MODEL_ZY);
                } else if (StrUtil.isNotEmpty(jsonObject.getString(SysConstant.FIELD_OBJ_ID))) {
                    //台账表 数据
                    jsonObject.put(SysConstant.MODEL_TYPE, SysConstant.MODEL_TZ);
                    model_type = SysConstant.MODEL_TZ;
                } else {
                    //两个字段都不存在
                    throw new BizException("设备[" + jsonObject.getString("sbmc") + "]：缺失sbid、obj_id字段");
                }

                //3、查询当前设备模型数据
                Map<String, Object> modelmeta = tyDao.getModelNameByType(null, sbzlx);
                if (modelmeta == null) {
                    throw new BizException("设备信息有误或不存该类设备！");
                }
                String modelName = MapUtil.getStr(modelmeta, SysConstant.FIELD_MODELNAME);
                if (StrUtil.isEmpty(modelName)) {
                    throw new BizException("设备子类型[" + sbzlx + "]模型：缺失modelname字段");
                }
                jsonObject.put("modelName", modelName);
                jsonObject.put("classid", modelmeta.get("classid"));
                String geotype = MapUtil.getStr(modelmeta, "geotype");
                jsonObject.put("geotype", shapeUtil.geoTypeToFourFigure(geotype));

                String currSbid;
                if (model_type == SysConstant.MODEL_ZY) {
                    currSbid = jsonObject.getString(SysConstant.FIELD_SBID);
                } else {
                    currSbid = jsonObject.getString(SysConstant.FIELD_OBJ_ID);
                }

                //4、处理公共参数部分
                //1. 拼接表名 添加前缀
                String zyTableName = StrUtil.addPrefixIfNot(modelName, SysConstant.PREFIX_TABLE_ZY);//资源基表名
                String txTableName = StrUtil.addPrefixIfNot(modelName, SysConstant.PREFIX_TABLE_TX);//图形基表名
 /*               jsonObject.put(SysConstant.FIELD_TX_TABLE, txTableName);
                jsonObject.put(SysConstant.FIELD_ZY_TABLE, zyTableName);
                String txTableName = SysConstant.PREFIX_TABLE_TX+modelName;
                String zyTableName = SysConstant.PREFIX_TABLE_ZY+modelName;*/
                //5、部分传入字段的处理
                if (StrUtil.isNotEmpty(jsonObject.getString("taskId"))) {
                    jsonObject.put("versionid", jsonObject.get("taskId"));//任务id
                }
                if (StrUtil.isNotEmpty(jsonObject.getString("versionid"))) {
                    jsonObject.put("taskId", jsonObject.get("versionid"));//任务id
                }

                //5.1、判断资源数据是否已存在
                boolean existZy = false;
                List<JSONObject> zyList = this.getDeviceList2(jsonObject);
                if (zyList != null && zyList.size() > 1) {
                    existZy = true;
                }
                //7.2、判断台账数据是否已存在
                boolean existTz = false;
                String sbTableName = tyDao.getTableNameByModelName(txTableName.toUpperCase());//大写查找
                JSONObject tzData = null;
                if (StrUtil.isEmpty(sbTableName)) {
                    log.info("-----------------" + txTableName + "无台账表------------");
                } else {
                    tzData = tyDao.getTzData(sbTableName, currSbid);
                    if (tzData != null && StrUtil.isNotEmpty(tzData.getString(SysConstant.FIELD_OBJ_ID))) {
                        existTz = true;
                    }
                }
                //如果当前为资源表的数据，直接判断如果存在就终止，台账则跳过
                jsonObject.put("addflag", SysConstant.operate_add);//建模
                if (model_type == SysConstant.MODEL_ZY) {
                    //处理资源
                    if (existZy) {
                        throw new BizException("sbid为[" + currSbid + "]的设备已存在图形数据,请不要重复新增!");
                    }
                    //添加资源+图形（1.都没有 2.有台账，无资源）
                    // 6.1、新建资源
                    result = this.insertDevice2(jsonObject, zyTableName.toLowerCase(), offset);
                    if (!result.isSuccess()) {
                        throw new BizException(result.getMsg());
                    } else {
//                        log.info("新建资源成功,sbid：{}",currSbid);
                    }
                    // 6.2、新建图形
                    JSONObject zy = (JSONObject) result.getData();
                    jsonObject.put("zyid", zy.get("oid"));
                    result = this.insertDevice2(jsonObject, txTableName.toLowerCase(), offset);
                    if (!result.isSuccess()) {
                        throw new BizException(result.getMsg());
                    } else {
//                        log.info("新建图形成功,sbid：{}",currSbid);
                    }
                } else {
                    //处理台账
                    if (existTz) {
                        throw new BizException("sbid为[" + currSbid + "]的设备已存在台账数据,请不要重复新增!");
                    }
                    //添加台账（1.都没有 2.有资源，无台账）
                    //特殊字段处理
                    if (StrUtil.isNotEmpty(sbTableName)) {
                        specialFieldValidation(jsonObject);
                        result = this.insertDevice2(jsonObject, sbTableName.toLowerCase(), offset);
                    }
                }

                /**
                 * 7 维护拓扑
                 */
                List<String> connection1 = new ArrayList<>();
                if (jsonObject.get("connection") != null) {//端子号
//                    log.info("=============保存端子号connection==================");
//                    if (!"11000000".equals(sbzlx) && !"11000001".equals(sbzlx) && !"30200002".equals(sbzlx) && !"30200003".equals(sbzlx)){
                    JSONArray connection = jsonObject.getJSONArray("connection");
                    for (int j = 0; j < connection.size(); j++) {
                        connection1.add(connection.getString(j));
                    }
//                    }
                } else {
//                    log.info("=============保存端子号conNO==================");
                    //点-端子
                    if (jsonObject.get("conNO") != null && StrUtil.isNotEmpty(jsonObject.getString("conNO"))) {
                        connection1.add(jsonObject.getString("conNO"));
                    }
                    //线-端子

                    if (jsonObject.get("qdConNO") != null && StrUtil.isNotEmpty(jsonObject.getString("qdConNO"))
                            && jsonObject.get("zdConNO") != null && StrUtil.isNotEmpty(jsonObject.getString("zdConNO"))) {
                        connection1.add(jsonObject.getString("qdConNO"));
                        connection1.add(jsonObject.getString("zdConNO"));
                    }
                }
                if (connection1.size() > 0) {
                    jsonObject.put("connection", connection1);
                    String taskId = jsonObject.getString("taskId");
                    int te = topoDao.getMaxTerminalByVersionid(taskId);
//                    log.info("维护拓扑");
                    result = this.insertTopo(jsonObject, te + i);
                    if (!result.isSuccess()) {
                        throw new BizException(result.getMsg());
                    } else {
                        log.info("=============保存端子号成功==================");
                    }
                }
            }
        } catch (Exception e) {
            log.error("autoCreateMode2执行异常，数据回滚", e);
            throw new BizException("批量建模失败！", e);
        }
        log.info("autoCreateModel2最终成功");
        return ResponseResult.success(null, "建模成功");
    }

    @Override
    public List<JSONObject> getDeviceList2(JSONObject jsonObject) {
        String zyTableName = jsonObject.getString(SysConstant.FIELD_ZY_TABLE);
        String txTableName = jsonObject.getString(SysConstant.FIELD_TX_TABLE);

        JSONObject param = new JSONObject();//查询参数
        //1. 设置表名
        param.put(SysConstant.FIELD_ZY_TABLE, StrUtil.addSuffixIfNot(zyTableName, SysConstant.SUFFIX_TABLE_VER));
        param.put(SysConstant.FIELD_TX_TABLE, StrUtil.addSuffixIfNot(txTableName, SysConstant.SUFFIX_TABLE_VER));
        String sbid = jsonObject.getString(SysConstant.FIELD_SBID);
        if (StrUtil.isNotBlank(sbid)) {
            param.put(SysConstant.FIELD_SBID, sbid);
        }
        String sbzlx = jsonObject.getString(SysConstant.FIELD_SBZLX);
        if (StrUtil.isNotBlank(sbzlx)) {
            param.put(SysConstant.FIELD_SBZLX, sbzlx);
        }
        String versionid = jsonObject.getString(SysConstant.FIELD_VERSIONID);
        if (StrUtil.isNotBlank(versionid)) {
            param.put(SysConstant.FIELD_VERSIONID, versionid);
        }
        if (jsonObject.get("customSql") != null && StrUtil.isNotEmpty(jsonObject.getString("customSql"))) {
            param.put("customSql", jsonObject.get("customSql"));
        }

        /**
         * 3、返回数据shape取值
         */
        List<JSONObject> deviceMainList = deviceDao.getDeviceMainList(param);
//        log.info("返回设备:"+JSONObject.toJSONString(list));
        return deviceMainList;
    }

    @Override
    public JSONObject getInsertDeviceSql2(JSONObject device, String tableName, List<Double> offset) {
        Map<String, Object> entity = new HashMap<>();
        StringBuilder fieldKey = new StringBuilder();//sql封装字段
        StringBuilder fieldValue = new StringBuilder();//sql封装值
        String currSbid = "";
        if (device.getInteger(SysConstant.MODEL_TYPE) == SysConstant.MODEL_ZY) {
            currSbid = device.getString(SysConstant.FIELD_SBID);
        } else {
            currSbid = device.getString(SysConstant.FIELD_OBJ_ID);
        }
        //查询表字段的基本信息（字段名，类型，长度，注释）
        String tbName = StrUtil.builder(tableName, (tableName.contains(SysConstant.PREFIX_TABLE_SB) ? "" : SysConstant.SUFFIX_TABLE_VER)).toString();
        List<Map> fieldList = tyDao.getFieldFormTablename(tbName);
        if (fieldList == null || fieldList.size() == 0) {
            throw new BizException("设备id[" + currSbid + "]查询不到表字段信息！");
        }

        //图形表
        if (tableName.contains(SysConstant.PREFIX_TABLE_TX)) {
            if (StrUtil.isEmpty(device.getString(SysConstant.FIELD_OID))) {
                throw new BizException("设备id[" + currSbid + "]的oid不能为空！");
            }

            // 坐标处理
            List<Point> points1 = new ArrayList<>();
            if (device.get(SysConstant.FIELD_POINTS) != null && device.get("geotype") != null) {//坐标
                JSONArray points = device.getJSONArray(SysConstant.FIELD_POINTS);
                for (int j = 0; j < points.size(); j++) {
                    Point point = JSONObject.parseObject(points.getString(j), Point.class);
                    points1.add(point);
                }
            } else if (StrUtil.isNotEmpty(device.getString(SysConstant.FIELD_SHAPE))) {
                points1 = JSON.parseArray(device.getString(SysConstant.FIELD_SHAPE), Point.class);
            } else {
                if (device.get("x") != null && device.get("y") != null) {
                    points1.add(new Point(device.getDouble("x"), device.getDouble("y")));
                }
                if (device.get("qdsbX") != null && device.get("qdsbY") != null
                        && device.get("zdsbX") != null && device.get("zdsbY") != null) {
                    if (device.get("zxdsbX") != null && device.get("zxdsbY") != null) {//中心点设备(变压器)
                        points1.add(new Point(device.getDouble("zxdsbX"), device.getDouble("zxdsbY")));
                    }
                    points1.add(new Point(device.getDouble("qdsbX"), device.getDouble("qdsbY")));
                    points1.add(new Point(device.getDouble("zdsbX"), device.getDouble("zdsbY")));
                }
            }
            String shape = shapeUtil.dealAddDeviceShape(points1, device.getString("geotype"), offset);
            device.put(SysConstant.FIELD_SHAPE, shape);
            tableName = StrUtil.builder("dwzy.", tableName, SysConstant.SUFFIX_TABLE_VER).toString();
        }
        //资源表
        if (tableName.contains(SysConstant.PREFIX_TABLE_ZY)) {
            device.put("istail", device.get("isfirst") == null ? "0" : device.get("isfirst"));
            tableName = StrUtil.builder("dwzy.", tableName, SysConstant.SUFFIX_TABLE_VER).toString();
        }

        //台账表
        if (tableName.contains(SysConstant.PREFIX_TABLE_SB)) {
            device = ParamSet.validTZField(device);
//            tableName="scyw."+tableName;
            tableName = StrUtil.builder("scyw.", tableName).toString();
        }

        // 编辑sql
        for (Map fieldObj : fieldList) {
            String attname = fieldObj.get("attname").toString().trim(); //表字段名  sbid/sbmc
            String typename = fieldObj.get("typname").toString().trim(); //表类型名 int4/varchar/numeric
            for (String key : device.keySet()) {
                //设备的key和字段名相同，并且值不为空，进行长度校验
                if (StrUtil.equals(attname, key.trim()) && device.get(key) != null) {
                    //字段限制长度不为空判断
                    if (fieldObj.get("fieldlength") != null && !SysConstant.FIELD_OID.equals(key)) {
                        int fieldlength = (int) fieldObj.get("fieldlength");
                        if (device.getString(key).length() > fieldlength) {
                            if (StrUtil.equals("yxbh", key) || StrUtil.equals("SBMC", key) || StrUtil.equals("SBBM", key) || StrUtil.equals("BDZMC", key)) {
                                int objLength = ByteUtils.getStringByteLength(device.get(key).toString(), "GBK");
                                if (objLength > fieldlength) {
                                    String objValue = ByteUtils.subString4Byte(device.get(key).toString(), fieldlength, "GBK");
                                    device.put(key, objValue);
                                }
                            } else {
                                throw new BizException("设备id[" + currSbid + "]参数字段[" + key + "=" + device.get(key) + "]超过最大长度:" + fieldlength);
                            }
                        }
                    }
                    //拼接sql的 field 和 values，例如： insert into xx(fieldKey) values(fieldValue)
                    if (StrUtil.isNotEmpty(device.getString(key))) {
                        fieldKey.append(key).append(",");
                        Object fieldValue1;
                        if (typename.contains("int") || typename.contains("geometry")) {//字符串,坐标
                            fieldValue1 = device.get(key);
                        } else if (typename.contains("date")) {//日期
                            fieldValue1 = "date('" + device.get(key) + "')";
                        } else {
                            fieldValue1 = "'" + device.get(key) + "'";
                        }
                        fieldValue.append(fieldValue1).append(",");
                        entity.put(key, fieldValue1);
                        break;
                    }
                }
            }
        }

        if (StrUtil.isEmpty(fieldKey.toString()) || StrUtil.isEmpty(fieldValue.toString())) {
            throw new BizException("设备id[\"+currSbid+\"]传入参数非符合要求参数！");
        }
        String key = fieldKey.toString().substring(0, fieldKey.length() - 1);
        String value = fieldValue.toString().substring(0, fieldValue.length() - 1);

        JSONObject result = new JSONObject();
        result.put("tableName", tableName);
        result.put("fieldKey", key);
        result.put("fieldValue", value);
        return result;
    }


    /**
     * 传入设备信息+表名（新增数据）_ver表
     *
     * @param device
     * @param tableName
     * @return
     */
    @Override
    public ResponseResult insertDevice2(JSONObject device, String tableName, List<Double> offset) {

        Map<String, Object> entity = new HashMap<>();
        StringBuilder fieldKey = new StringBuilder();//sql封装字段
        StringBuilder fieldValue = new StringBuilder();//sql封装值
        String currSbid = "";
        if (device.getInteger(SysConstant.MODEL_TYPE) == SysConstant.MODEL_ZY) {
            currSbid = device.getString(SysConstant.FIELD_SBID);
        } else {
            currSbid = device.getString(SysConstant.FIELD_OBJ_ID);
        }
        //取表字段名称
        String tbName = StrUtil.builder(tableName, (tableName.contains(SysConstant.PREFIX_TABLE_SB) ? "" : SysConstant.SUFFIX_TABLE_VER)).toString();
        List<Map> fieldList = tyDao.getFieldFormTablename(tbName);
        if (CollUtil.isEmpty(fieldList)) {
//            return new ResponseResult(false, "设备id[" + currSbid + "]查询不到表字段信息！", device);
            throw new BizException("设备id[" + currSbid + "]查询不到表字段信息！");
        }

        //图形表
        if (tableName.contains(SysConstant.PREFIX_TABLE_TX)) {
            if (StrUtil.isEmpty(device.getString(SysConstant.FIELD_OID))) {
                long oid = tyDao.getUUOID("'dwzy.seq_" + tableName + "_oid'");
                device.put(SysConstant.FIELD_OID, oid);
            }

            // 坐标处理
            List<Point> points1 = new ArrayList<>();

            if (device.get(SysConstant.FIELD_POINTS) != null && device.get("geotype") != null) {//坐标
                JSONArray points = device.getJSONArray(SysConstant.FIELD_POINTS);
                for (int j = 0; j < points.size(); j++) {
                    Point point = JSONObject.parseObject(points.getString(j), Point.class);
                    points1.add(point);
                }
            } else if (StrUtil.isNotEmpty(device.getString(SysConstant.FIELD_SHAPE))) {
                points1 = JSON.parseArray(device.getString("shape"), Point.class);
            } else {
                if (device.get("x") != null && device.get("y") != null) {
                    points1.add(new Point(device.getDouble("x"), device.getDouble("y")));
                }
                if (device.get("qdsbX") != null && device.get("qdsbY") != null
                        && device.get("zdsbX") != null && device.get("zdsbY") != null) {
                    if (device.get("zxdsbX") != null && device.get("zxdsbY") != null) {//中心点设备(变压器)
                        points1.add(new Point(device.getDouble("zxdsbX"), device.getDouble("zxdsbY")));
                    }
                    points1.add(new Point(device.getDouble("qdsbX"), device.getDouble("qdsbY")));
                    points1.add(new Point(device.getDouble("zdsbX"), device.getDouble("zdsbY")));
                }
            }
            String shape = shapeUtil.dealAddDeviceShape(points1, device.getString("geotype"), offset);
            device.put(SysConstant.FIELD_SHAPE, shape);
            tableName = StrUtil.builder("dwzy.", tableName, SysConstant.SUFFIX_TABLE_VER).toString();
//            log.info("-----------------新建图形："+tableName+"------------");
        }
        //资源表
        if (tableName.contains(SysConstant.PREFIX_TABLE_ZY)) {
            device.put("istail", device.get("isfirst") == null ? "0" : device.get("isfirst"));
            tableName = StrUtil.builder("dwzy.", tableName, SysConstant.SUFFIX_TABLE_VER).toString();
//            log.info("-----------------新建资源："+tableName+"------------");
        }

        //台账表
        if (tableName.contains(SysConstant.PREFIX_TABLE_SB)) {
            device = ParamSet.validTZField(device);
//            tableName = "scyw." + tableName;
            tableName = StrUtil.builder("scyw.", tableName).toString();
//            log.info("-----------------新建台账："+tableName+"------------");
        }


        // 编辑sql
        for (Map fieldObj : fieldList) {
            String attname = fieldObj.get("attname").toString().trim();
            String typename = fieldObj.get("typname").toString().trim();
            for (String key : device.keySet()) {
                if (StrUtil.equals(attname, key.trim()) && device.get(key) != null) {
                    //字段限制长度不为空判断
                    if (fieldObj.get("fieldlength") != null && !SysConstant.FIELD_OID.equals(key)) {
                        int fieldlength = (int) fieldObj.get("fieldlength");
                        if (device.get(key).toString().length() > fieldlength) {
                            if (StrUtil.equals("yxbh", key) || StrUtil.equals("SBMC", key) || StrUtil.equals("SBBM", key) || StrUtil.equals("BDZMC", key)) {
                                int objLength = ByteUtils.getStringByteLength(device.get(key).toString(), "GBK");
                                if (objLength > fieldlength) {
                                    String objValue = ByteUtils.subString4Byte(device.get(key).toString(), fieldlength, "GBK");
                                    device.put(key, objValue);
                                }
                            } else {
                                throw new BizException("设备id[" + currSbid + "]参数字段[" + key + "=" + device.get(key) + "]超过最大长度:" + fieldlength);
                            }
                        }
//                        if(device.get(key).toString().length()>fieldlength){
//                            return new ResponseResult(false,"参数字段["+key+"]超过最大长度:"+fieldlength,device);
//                        }
                    }
                    if (device.get(key) != null && StrUtil.isNotEmpty(device.get(key).toString())) {
                        fieldKey.append(key).append(",");
                        Object fieldValue1 = "";
                        if (typename.contains("int") || typename.contains("geometry")) {//字符串,坐标
                            fieldValue1 = device.get(key);
                        } else if (typename.contains("date")) {//日期
                            fieldValue1 = "date('" + device.get(key) + "')";
                        } else {
                            fieldValue1 = "'" + device.get(key) + "'";
                        }
                        fieldValue.append(fieldValue1).append(",");
                        entity.put(key, fieldValue1);
                        break;
                    }
                }
            }
        }

        if (StrUtil.isEmpty(fieldKey.toString()) || StrUtil.isEmpty(fieldValue.toString())) {
            throw new BizException("设备id[\"+currSbid+\"]传入参数非符合要求参数！");
        }
        String key = fieldKey.toString().substring(0, fieldKey.length() - 1);
        String value = fieldValue.toString().substring(0, fieldValue.length() - 1);

        Map param = new HashMap();
        param.put("tableName", tableName);
        param.put("fieldKey", key);
        param.put("fieldValue", value);
        deviceDao.insertDeviceModel(param);
        return ResponseResult.success(device, "新建成功");
    }

    @Override
    public JSONObject insertTopoSql(JSONObject device, int terminalid, String[] cons) {
        if (StrUtil.isEmpty(device.getString(SysConstant.FIELD_VERSIONID)) || StrUtil.isEmpty(device.getString(SysConstant.FIELD_OID))
                || StrUtil.isEmpty(device.getString("addflag")) || StrUtil.isEmpty(device.getString(SysConstant.FIELD_SBZLX))
                || StrUtil.isEmpty(device.getString("connection"))) {
            throw new BizException("端子号保存失败，参数有误(versionid/addflag/sbzlx/connection)");
        }
        StringBuilder fieldKey = new StringBuilder("oid, state_id, versionid, addflag, sboid, sbzlx, terminalid, topnodeid");
        StringBuilder fieldValue = new StringBuilder();
        for (int i = 0; i < cons.length; i++) {
            long oid = tyDao.getUUOID("'topo.seq_" + SysConstant.SEQ_TOPO + "_oid'");
            fieldValue.append("(");
            fieldValue.append(oid).append(",");//oid
            fieldValue.append("11111111").append(",");//state_id
            fieldValue.append(device.getInteger("versionid")).append(",");//versionid
            fieldValue.append(device.getInteger("addflag")).append(",");//addflag
            fieldValue.append(device.getString("oid")).append(",");//sboid
            fieldValue.append(device.getInteger("sbzlx")).append(",");//sbzlx
            fieldValue.append(terminalid).append(",");//terminalid
            fieldValue.append(cons[i]);//topnodeid
            fieldValue.append(")");
            if (i != cons.length - 1) {
                fieldValue.append(",");
            }
        }

        JSONObject result = new JSONObject();
        result.put("tableName", SysConstant.TOPO_TABLE);
        result.put("fieldKey", fieldKey.toString());
        result.put("fieldValue", fieldValue.toString());
        return result;
    }

    @Override
    public ResponseResult<List<JSONObject>> getCurrentDevicePros(JSONObject jsonObject) {
        log.info("getCurrentDevicePros原始参数：{}", jsonObject);
        String tqsbid = jsonObject.getString("tqsbid");
        if (StrUtil.isBlank(tqsbid)) {
            return ResponseResult.failed("任务tqsbid不为空！");
        }
//        List<Map<String,Object>> problemList =this.getTaskProList(jsonObject);
        QueryWrapper<Map<String, Object>> wrapper = new QueryWrapper();
        if (StrUtil.isNotEmpty(tqsbid)) {
            wrapper.eq("t.tqsbid", tqsbid);
        }
        String sbid = jsonObject.getString("sbid");
        if (StrUtil.isNotEmpty(sbid)) {
            wrapper.eq("t.sbid", sbid);
        }
        String searchname = jsonObject.getString("searchname");//模糊查询
        if (StrUtil.isNotEmpty(searchname)) {
            wrapper.like("t.sbname", searchname).or().like("t.wtname", searchname);
        }
        String yxdw = jsonObject.getString("yxdw");
        if (StrUtil.isNotEmpty(yxdw)) {
            wrapper.eq("t.yxdw", yxdw);
        }
        String sbname = jsonObject.getString("sbname");
        if (StrUtil.isNotEmpty(sbname)) {
            wrapper.like("t.sbname", sbname);
        }
        int sbzlx = jsonObject.getInteger("sbzlx");
        if (jsonObject.get("sbzlx") != null && sbzlx != 0) {
            wrapper.eq("t.sbzlx", sbzlx);
        }
        int sboid = jsonObject.getInteger("sboid");
        if (jsonObject.get("sboid") != null && sboid != 0) {
            wrapper.eq("t.sboid", sboid);
        }

        int gdoid = jsonObject.getInteger("gdoid");
        if (jsonObject.get("gdoid") != null && gdoid != 0) {
            wrapper.eq("t.gdoid", gdoid);
        }
        wrapper.orderByAsc("t.state");
        List<JSONObject> currentDevicePros = deviceDao.getCurrentDevicePros(wrapper);
//        log.info("getCurrentDevicePros最终返回数据：{}", new A);
        return ResponseResult.success(currentDevicePros);
    }

    @Override
    public ResponseResult<JSONObject> getNewSer(JSONObject jsonObject) {
        log.info("getNewSer原始参数：{}", jsonObject);
        try {
            JSONObject resultData = new JSONObject();
            for (String key : jsonObject.keySet()) {
                JSONArray jsonArray = jsonObject.getJSONArray(key);//获取"newSerno"中的值
                Map<String, Object> mapList = new HashMap<>();
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject1 = jsonArray.getJSONObject(i);//获取sbzlx
                    Map<String, Object> map = new HashMap<String, Object>();//子对象
                    for (String key1 : jsonObject1.keySet()) {
                        if (jsonObject1.get(key1) != null) {
                            map.put(key1, jsonObject1.get(key1).toString());//key1 == sbzlx
                        }
                    }
                    String zwtype = null;
                    if (map.get("zwtype") != null && StrUtil.isNotEmpty(map.get("zwtype").toString())) {
                        zwtype = map.get("zwtype").toString();
                    }
                    String sbzlx = map.get("sbzlx").toString();

                    //序列号和端子号判断
                    String modelname = "";
                    String no = "";
                    //根据序列类型区分，并通过sbzlx获取对应的表信息，在通过表名，去代理获取gis库中新的序列号
                    if (StrUtil.equals("newSerno", key)) {
                        Map modelType = tyDao.getModelNameByType(null, sbzlx);
                        if (modelType == null) {
                            continue;
                        }
                        modelname = modelType.get("modelname").toString();
                        no = dataBrokerUtil.getOid((SysConstant.PREFIX_TABLE_TX + modelname).toUpperCase());
//                        no=String.valueOf(tyDao.getUUOID("'dwzy.seq_"+SysConstant.pre_table_tx+modelname+"_oid'"));
                    }
                    if (StrUtil.equals("newSerZyno", key)) {
                        Map modelType = tyDao.getModelNameByType(null, sbzlx);
                        if (modelType == null) {
                            continue;
                        }
                        modelname = modelType.get("modelname").toString();
                        no = String.valueOf(tyDao.getUUOID("'dwzy.seq_" + SysConstant.PREFIX_TABLE_ZY + modelname + "_oid'"));

                    }
                    if (StrUtil.equals("newConno", key)) {
                        String topoTable = SysConstant.SEQ_TOPO;
//                        no=String.valueOf(tyDao.getUUOID("'topo.seq_"+topoTable+"_oid'"));
                        no = dataBrokerUtil.getOid(SysConstant.GIS_CONF_TOPORELATION);
                    }
                    if (StrUtil.equals("newSBID", key)) {
                        no = AwayTools.getUUID42();
                    }
                    if (StrUtil.equals("newSBLX", key)) {
                        Map sblx = tyDao.getSblxInfoBySbzlx(sbzlx);
                        if (sblx != null) {
                            JSONObject noObj = new JSONObject();
                            noObj.put("sblxbm", sblx.get("sblxbm"));
                            noObj.put("sblxmc", sblx.get("sblx"));
                            no = noObj.toJSONString();
                        } else {
                            no = "";
                        }
                    }
                    map.put("no", no);

                    String iStr = i < 10 ? "0" + i : i + "";//判断小于两位数

                    if (map.get("zwtype") != null && StrUtil.isNotEmpty(map.get("zwtype").toString())) {
                        mapList.put(zwtype + iStr, map);
                    } else {
                        mapList.put(sbzlx + iStr, map);//区分相同的zwtype
                    }
                }

                //获取相同的sbzlx为一组
                List<String> sameStr = new ArrayList();
                for (String sameKey : mapList.keySet()) {
                    sameKey = sameKey.substring(0, sameKey.length() - 2);
                    if (sameStr.contains(sameKey)) {
                        continue;
                    }
                    sameStr.add(sameKey);
                }

                Map<String, Object> sameMap = new HashMap<>();//容器
                for (String sameString : sameStr) {
                    List sameList = new ArrayList();
                    for (String sameKey : mapList.keySet()) {
                        String sameKey1 = sameKey.substring(0, sameKey.length() - 2);
                        if (StrUtil.equals(sameString, sameKey1)) {
                            sameList.add(mapList.get(sameKey));
                        }
                    }
                    sameMap.put(sameString, sameList);
                }
                resultData.put(key, sameMap);
            }
            log.info("getNewSer最终返回：{}" + JSONObject.toJSONString(resultData));
            return ResponseResult.success(resultData);
        } catch (Exception e) {
            log.error("获取新的序列号失败", e);
            return ResponseResult.failed("获取新的序列号失败");
        }
    }

    @Override
    public List<TYwTaskYk> getWorkOrderDetail(String gdType, String taskId) {
        return deviceDao.getWorkOrderDetail(Integer.parseInt(gdType), taskId);
    }

    @Override
    public ResponseResult insertXL(JSONObject object) {
        if (object.get("xlList") == null) {
            throw new BizException("insertXL入参不能为空");
        }
        String xlList = object.getString("xlList");
        log.info("insertXL原始参数：{}", xlList);
        try {
            JSONObject param = new JSONObject();
            param.put("modeldatas", xlList);
            return this.autoCreateModel2(param);
        } catch (Exception e) {
            log.error("新建线路失败!", e);
            return ResponseResult.failed(e.getMessage(), "新建线路失败!");
        }
    }

    @Override
    public ResponseResult insertTopo(JSONObject device, int terminalid) {
        if (StrUtil.isEmpty(device.getString(SysConstant.FIELD_VERSIONID)) || StrUtil.isEmpty(device.getString(SysConstant.FIELD_OID))
                || StrUtil.isEmpty(device.getString("addflag")) || StrUtil.isEmpty(device.getString(SysConstant.FIELD_SBZLX))
                || StrUtil.isEmpty(device.getString("connection"))) {
            return new ResponseResult(false, "端子号保存失败(versionid/addflag/sbzlx/connection)", device);
        }
        JSONArray connection = device.getJSONArray("connection");
        for (int i = 0; i < connection.size(); i++) {
   /*         TopoEntity topo = new TopoEntity();
            topo.setOid(tyDao.getUUOID("'topo.seq_" + SysConstant.seq_topo + "_oid'") + "");
            topo.setVersionid(device.getInteger("versionid"));
            topo.setTopnodeid(connection.getInteger(i));
            topo.setSbzlx(device.getInteger("sbzlx"));
            topo.setAddflag(device.getInteger("addflag"));
            topo.setTerminalid(terminalid);
            topo.setSboid(device.getString("oid"));
            topo.setState_id("11111111");
            topoDao.insertDeviceTopo(topo);*/
            ConfToporelationXxVer topo = new ConfToporelationXxVer();
            topo.setOid(tyDao.getUUOID("'topo.seq_" + SysConstant.SEQ_TOPO + "_oid'"))
                    .setVersionid(device.getBigDecimal("versionid"))
                    .setTopnodeid(Long.valueOf(connection.getInteger(i)))
                    .setSbzlx(device.getInteger("sbzlx"))
                    .setAddflag(device.getInteger("addflag"))
                    .setTerminalid(terminalid)
                    .setSboid(device.getLong("oid"))
                    .setStateId(BigDecimal.valueOf(11111111));
            toporelationService.save(topo);
        }
        return new ResponseResult(true, "拓扑关系建立成功!", device);
    }

    @Override
    public ResponseResult<IPage<JSONObject>> getDevicesFromTQ(JSONObject jsonObject) {
        log.info("getDevicesFromTQ原始参数：" + jsonObject.toJSONString());
        try {
            String gdtype = jsonObject.getString(SysConstant.FIELD_GDTYPE);
            String versionid = jsonObject.getString(SysConstant.FIELD_VERSIONID);
            //判断条件
            if (StrUtil.isBlank(gdtype) || StrUtil.isBlank(versionid)) {
                throw new BizException("工单类型/版本号不为空!");
            }
            StrBuilder customSql = StrBuilder.create();
            //设备类型
            String sbzlxsJson = jsonObject.getString("sbzlxs");
            if (StrUtil.isNotBlank(sbzlxsJson) && sbzlxsJson.indexOf("[") == 0) {
                JSONArray sbzlxs = jsonObject.getJSONArray("sbzlxs");
                StrBuilder sbzlx = StrBuilder.create();
                for (int i = 0; i < sbzlxs.size(); i++) {
                    if (StrUtil.isNotEmpty(sbzlxs.getString(i))) {
//                        sbzlx = sbzlx + "'" + sbzlxs.getString(i) + "',";
                        sbzlx.append("'").append(sbzlxs.getString(i)).append("',");
                    }
                }
                if (sbzlx.hasContent()) {
                    String sbzlx1 = sbzlx.subString(0, sbzlx.length() - 1);
//                    String sbzlx1 = sbzlx.substring(0, sbzlx.length() - 1);
                    customSql.append(" and t.sbzlx in (").append(sbzlx1).append(")");
                }
            }
            //所属电站
            String ssdz = jsonObject.getString("ssdz");
            if (StrUtil.isNotEmpty(ssdz)) {
                customSql.append(" and t.ssdz ='").append(ssdz).append("'");
            }
            if (customSql.hasContent()) {
                jsonObject.put("customSql", customSql.toString());
            }
            //计算条数
            List<JSONObject> count = this.getDeviceTqList(jsonObject);
            // 获取分页参数
            int currPage = jsonObject.getInteger(SysConstant.FIELD_CURR_PAGE) == null ? 1 : jsonObject.getInteger(SysConstant.FIELD_CURR_PAGE);
            int pageSize = jsonObject.getInteger(SysConstant.FIELD_PAGE_SIZE) == null ? 20 : jsonObject.getInteger(SysConstant.FIELD_PAGE_SIZE);
            jsonObject.put("currPage", currPage);
            jsonObject.put("pageSize", pageSize);
            customSql.append(" LIMIT ").append(String.valueOf(pageSize)).append(" OFFSET ").append(String.valueOf((currPage - 1) * pageSize));
            jsonObject.put("customSql", customSql.toString());
            List<JSONObject> tqList = this.getDeviceTqList(jsonObject);
            for (JSONObject entity : tqList) {
                //台区数据端子号获取
                if (entity.get("toponodeid") != null) {
                    String conn = entity.get("toponodeid").toString().replaceAll(",", "|");
                    entity.put("conn", conn);
                }
                if (entity.get("ssjg") == null) {
                    continue;
                }
                //除了站内连接线的ssjg数据
                JSONObject paramSSJG = new JSONObject();
                paramSSJG.put(SysConstant.FIELD_GDTYPE, jsonObject.get(SysConstant.FIELD_GDTYPE));
                paramSSJG.put(SysConstant.FIELD_VERSIONID, jsonObject.get(SysConstant.FIELD_VERSIONID));
                paramSSJG.put("customSql", " and t.ssjg =" + entity.get("ssjg") + " and t.sbzlx <>" + SysConstant.MODELID_ZNLJX + "");
                List<JSONObject> ssjgList = this.getDeviceTqList(paramSSJG);

                for (JSONObject entity1 : ssjgList) {
                    //出线点
                    if (StrUtil.equals(String.valueOf(SysConstant.MODELID_ZNCXD), entity1.getString("sbzlx"))) {
                        entity.put("qsdsb", entity1.get("oid"));
                        entity.put("qsdsblx", entity1.get("sbzlx"));
                    } else {
                        entity.put("cxkg", entity1.get("oid"));
                        entity.put("cxkglx", entity1.get("sbzlx"));
                    }
                }
            }

            IPage<JSONObject> page = new Page<>(currPage, pageSize);
            page.setRecords(tqList);
            page.setTotal(count.size());
            log.info("getDevicesFromTQ最终返回：" + JSONObject.toJSONString(page));
            return ResponseResult.success(page);
        } catch (Exception e) {
            log.error("获取任务内的变压器列表失败", e);
            return ResponseResult.failed("获取任务内的变压器列表失败：" + e.getMessage());
        }
    }

    @Override
    public ResponseResult<List<JSONObject>> getTopDevices(JSONObject jsonObject) {
        log.info("getTopDevices原始参数：" + jsonObject);
        try {
            // 1、参数判断
            String sbzlx = jsonObject.getString(SysConstant.FIELD_SBZLX);//设备子类型
            String oid = jsonObject.getString(SysConstant.FIELD_OID);//主键
            String gdtype = jsonObject.getString(SysConstant.FIELD_GDTYPE);
            String versionid = jsonObject.getString(SysConstant.FIELD_VERSIONID);
            if (StrUtil.isEmpty(sbzlx) || StrUtil.isEmpty(oid)
                    || StrUtil.isEmpty(gdtype) || StrUtil.isEmpty(versionid)) {
                throw new BizException("获取当前设备拓扑失败，参数有误(versionid/addflag/sbzlx/connection)");
            }
            Map<String, Object> modelType = tyDao.getModelNameByType(null, sbzlx);
            if (modelType == null) {
                throw new BizException("设备子类型不存在！");
            }
            String oids = "(t.sboid = " + oid + " and t.sbzlx = " + sbzlx + ")";// sql查询使用
            String classAndOid = modelType.get("classid") + "," + oid;//topo服务参数

            /**
             *  2、逻辑判断数据
             */
            //2.1 传入物理杆 去找运行杆的信息
            if (SysConstant.MODELIDS_WLG.contains(sbzlx)) {
                classAndOid = "";//topo不查询物理杆；清空
                JSONObject objParam = new JSONObject();
                objParam.put(SysConstant.FIELD_GDTYPE, gdtype);
                objParam.put(SysConstant.FIELD_VERSIONID, versionid);
                objParam.put("customSql", " and t.sswlg=" + oid);
                List<JSONObject> objList = this.getDeviceTqList(objParam);
                for (JSONObject entity : objList) {
                    oid = entity.getString(SysConstant.FIELD_OID);
                    sbzlx = entity.getString(SysConstant.FIELD_SBZLX);
                    Map<String, Object> modelObj = tyDao.getModelNameByType(null, sbzlx);
                    classAndOid = classAndOid + "|" + modelObj.get("classid") + "," + oid;
                    oids = oids + " or (t.sboid = " + oid + " and t.sbzlx = " + sbzlx + ")";
                }
                classAndOid = classAndOid.substring(1);
            }

            /**
             * 3、访问topo找关系
             */
            String peerObjectIds = "";
            log.info("请求topo服务地址：{}，原始参数：{}" , topoService, classAndOid);
            OMElement ome = TopoUtil.queryByObjectExtByDocument(topoService, "1001", classAndOid, "", "1", "");//
            if (ome == null) {
                log.warn("设备[{}]查无topo数据：", jsonObject);
            } else {
                Iterator i = ome.getChildElements();
                while (i.hasNext()) {
                    OMElement flag1 = (OMElement) i.next();
                    if ("PeerObjectIds".equals(flag1.getLocalName())) {
                        peerObjectIds = flag1.getText();
                        log.info("查找的topo设备返回的数据：" + peerObjectIds);
                        String[] obj = peerObjectIds.split(";");
                        for (String objEntity : obj) {
                            String[] others = objEntity.split("\\|");
                            for (String key : others) {
                                String[] device = key.split(",");
                                if (device.length > 1) {
                                    oids = oids + " or ( t.sboid =" + device[1] + " and t.classid =" + device[0] + " )";
                                }
                            }
                        }
                        break;
                    }
                }
            }
            /**
             * 4、本库数据集合格式化查询
             */
            JSONObject param = new JSONObject();
            param.put(SysConstant.FIELD_GDTYPE, gdtype);
            param.put(SysConstant.FIELD_VERSIONID, versionid);
            param.put("customSql", " and (" + oids + ")");
            List<JSONObject> list = this.getDeviceTqList(param);
            log.info("getTopDevices当前设备的下发原始数据：{}", JSON.toJSONString(list));
//            /**
//             * 获取设备的全部geotype
//             */
//            List<Map> modelList=tyDao.getModelNameByTypes();
//            Map<String,Object> modelMap =new HashMap();
//            for(Map modelEntity :modelList){
//                modelMap.put(modelEntity.get("modelid").toString(),modelEntity.get("geotype"));
//            }

            //通过代理获取设备信息
            List<JSONObject> resultData = new ArrayList<>();
            for (JSONObject agentEntity : list) {
                JSONObject device = dataBrokerUtil.getInfo(agentEntity.getString(SysConstant.FIELD_OID), agentEntity.getString(SysConstant.FIELD_SBZLX));
                if (device != null) {
                    device.put(SysConstant.FIELD_POINTS, agentEntity.get(SysConstant.FIELD_POINTS));
//                    device.put("geotype",shapeUtil.geoTypeToFourFigure(modelMap.get(device.getString("sbzlx")).toString()));
                    device.put("geotype", agentEntity.get("geotype"));
                    // 坐标处理
                    List<Point> points1 = new ArrayList<>();
                    if (agentEntity.get(SysConstant.FIELD_POINTS) != null && agentEntity.get("geotype") != null) {//坐标
                        JSONArray points = device.getJSONArray(SysConstant.FIELD_POINTS);
//                        log.info("getTopDevices当前设备{}的points数据：{}", device, points);
                        if (!points.isEmpty()) {
                          /*  for (int j = 0; j < points.size(); j++) {
                                log.info("getTopDevices转化points数据：{}",points.getString(j));
                                Point point = JSON.parseObject(JSON.parse(points.getString(j)).toString(), Point.class);
                                points1.add(point);
                            }*/
                            log.info("getTopDevices转化points数据：{}",agentEntity.getString(SysConstant.FIELD_POINTS));
                            points1 = points.toJavaList(Point.class);
                        }
                    }
                    String shape = shapeUtil.dealAddDeviceShape(points1, device.getString("geotype"), null);
                    device.put(SysConstant.FIELD_SHAPE, shape);
                    resultData.add(device);
                } else {
//                    agentEntity.put("geotype",shapeUtil.geoTypeToFourFigure(modelMap.get(device.getString("sbzlx")).toString()));
                    resultData.add(agentEntity);
                }
            }
            log.info("getTopDevices最终返回：{}", resultData);
            return ResponseResult.success(resultData);
        } catch (Exception e) {
            log.error("获取当前设备的topo关系失败", e);
            return ResponseResult.failed("获取当前设备的topo关系失败：" + e.getMessage());
        }
    }

    @Override
    public ResponseResult<JSONObject> updateDeviceShape(JSONObject jsonObject) {
        log.info("updateDevices原始参数：{}", jsonObject);
        try {
            if (jsonObject.get("updateModels") == null) {
                throw new BizException("updateDevices入参格式错误！");
            }
            String gdtype = jsonObject.getString(SysConstant.FIELD_GDTYPE);
            if (StrUtil.isEmpty(gdtype)) {
                throw new BizException("工单类型不能为空！");
            }
            JSONArray jsonArray = jsonObject.getJSONArray("updateModels");
            String param = dataBrokerUtil.formatData(jsonArray, SysConstant.operate_edit);
            String resultStr = dataBrokerUtil.update(param);
            if (StrUtil.isEmpty(resultStr)) {
                throw new BizException("代理修改服务出错，修改失败！");
            }
            if (!StrUtil.equals("updated", resultStr)) {
                throw new BizException(resultStr);
            }

            /**
             * 修改台区
             */
            Map<String, Object> updateParam = new HashMap<>();
            String tableName = SysConstant.TASK_STATE_TABLE.get(SysConstant.TASK_STATE_TQ);
            if (SysConstant.TASK_STATE_ZXS.contains(gdtype)) {
                tableName = SysConstant.TASK_STATE_TABLE.get(SysConstant.TASK_STATE_ZX);
            }
            updateParam.put("tableName", StrUtil.builder("ywsj.", tableName).toString());

            // 获取字段属性
            //取表字段名称
            List<Map> fieldList = tyDao.getFieldFormTablename(tableName);
            StringBuilder fieldSetting = new StringBuilder();
            StringBuilder fieldWhereSql = new StringBuilder();
            List<Double> offset = shapeUtil.getOffSet();
            for (int i = 0; i < jsonArray.size(); i++) {
                fieldWhereSql.setLength(0);//清空
                fieldWhereSql.append(" 1=1");
                JSONObject updateEntity = jsonArray.getJSONObject(i);
                if (updateEntity.get("oid") != null) {
                    fieldWhereSql.append(" and sboid =").append(updateEntity.get("oid"));
                }
                if (updateEntity.get("sbzlx") != null) {
                    fieldWhereSql.append(" and sbzlx =").append(updateEntity.get("sbzlx"));
                }
                if (updateEntity.get("sbid") != null) {
                    fieldWhereSql.append(" and sbid ='").append(updateEntity.get("sbid")).append("'");
                }
                if (updateEntity.get("classid") != null) {
                    fieldWhereSql.append(" and classid =").append(updateEntity.get("classid"));
                }

                fieldSetting.setLength(0);//清空
                for (Map fieldObj : fieldList) {
                    String attname = fieldObj.get("attname").toString().trim();
                    String typename = fieldObj.get("typname").toString().trim();
                    for (String key : updateEntity.keySet()) {
                        if (StrUtil.equals(attname, key.trim()) && updateEntity.get(key) != null) {
                            if (updateEntity.get(key) != null && StrUtil.isNotEmpty(updateEntity.get(key).toString())) {
                                fieldSetting.append(key).append("=");
                                Object fieldValue1 = "";
                                if (typename.contains("int")) {//字符串,坐标
                                    fieldValue1 = updateEntity.get(key);
                                } else if (typename.contains("geometry")) {
                                    // 坐标处理
                                    List<Point> points1 = new ArrayList<>();
                                    if (updateEntity.get("points") != null && updateEntity.get("geotype") != null) {//坐标
                                        JSONArray points = updateEntity.getJSONArray("points");
                                       /* for (int j = 0; j < points.size(); j++) {
                                            Point point = JSONObject.parseObject(points.getString(j), Point.class);
                                            points1.add(point);
                                        }*/
                                       if (!points.isEmpty()){
                                           points1 = points.toJavaList(Point.class);
                                       }
                                    }
                                    fieldValue1 = shapeUtil.dealAddDeviceShape(points1, updateEntity.getString("geotype"), offset);
                                } else if (typename.contains("date")) {//日期
                                    fieldValue1 = "date('" + updateEntity.get(key) + "')";
                                } else {
                                    fieldValue1 = "'" + updateEntity.get(key) + "'";
                                }
                                fieldSetting.append(fieldValue1).append(",");
                                break;
                            }
                        }
                    }
                }
                if (StrUtil.isEmpty(fieldSetting.toString())) {
                    continue;
                }
                updateParam.put("fieldSetting", fieldSetting.toString().substring(0, fieldSetting.toString().length() - 1));
                updateParam.put("fieldWhereSql", fieldWhereSql.toString());
                deviceDao.updateDeviceModel(updateParam);
            }
            ResponseResult<JSONObject> result = this.formatOutPic(jsonArray.toJavaList(JSONObject.class), jsonObject.getInteger("gdtype"));
            log.info("updateDevices最终返回：{}", JSONObject.toJSONString(result));
            return result;
        } catch (Exception e) {
            log.error("修改设备信息失败", e);
            return ResponseResult.failed("修改设备信息失败：" + e.getMessage());
        }
    }

    @Override
    public ResponseResult<JSONObject> deleteDevices(JSONObject jsonObject) {
        log.info("deleteDevices原始参数：{}", jsonObject);
        try {
            if (jsonObject.get("deleteModels") == null) {
                throw new BizException("deleteModels入参格式错误！");
            }
            String gdtype = jsonObject.getString(SysConstant.FIELD_GDTYPE);
            if (StrUtil.isEmpty(gdtype)) {
                throw new BizException("工单类型不能为空！");
            }

            JSONArray jsonArray = jsonObject.getJSONArray("deleteModels");
            String param = dataBrokerUtil.formatData(jsonArray, SysConstant.operate_del);
            String resultStr = dataBrokerUtil.delete(param);
            if (StrUtil.isEmpty(resultStr)) {
                throw new BizException("代理修改服务出错，修改失败！");
            }
            if (!StrUtil.equals("deleted", resultStr)) {
                throw new BizException(resultStr);
            }

            /**
             * 删除台区
             */
            Map updateParam = new HashMap();
            String tableName = SysConstant.TASK_STATE_TABLE.get(SysConstant.TASK_STATE_TQ);
            if (SysConstant.TASK_STATE_ZXS.contains(gdtype)) {
                tableName = SysConstant.TASK_STATE_TABLE.get(SysConstant.TASK_STATE_ZX);
            }
//            updateParam.put("tableName","ywsj."+tableName);
            updateParam.put("tableName", StrUtil.builder("ywsj.", tableName).toString());

            StringBuilder fieldWhereSql = new StringBuilder();
            for (int i = 0; i < jsonArray.size(); i++) {
                fieldWhereSql.setLength(0);//清空
                fieldWhereSql.append(" 1=1");
                JSONObject updateEntity = jsonArray.getJSONObject(i);
                if (updateEntity.get("oid") != null) {
                    fieldWhereSql.append(" and sboid =").append(updateEntity.get("oid"));
                }
                if (updateEntity.get("sbzlx") != null) {
                    fieldWhereSql.append(" and sbzlx =").append(updateEntity.get("sbzlx"));
                }
                if (updateEntity.get("sbid") != null) {
                    fieldWhereSql.append(" and sbid ='").append(updateEntity.get("sbid")).append("'");
                }
                if (updateEntity.get("classid") != null) {
                    fieldWhereSql.append(" and classid =").append(updateEntity.get("classid"));
                }
                updateParam.put("fieldWhereSql", fieldWhereSql.toString());
                deviceDao.deleteDeviceModel(updateParam);
            }
            ResponseResult<JSONObject> result = this.formatOutPic(jsonArray.toJavaList(JSONObject.class), jsonObject.getInteger("gdtype"));
            log.info("deleteDevices最终返回：{}", result);
            return result;

        } catch (Exception e) {
            log.error("删除设备信息失败", e);
            return ResponseResult.failed("删除设备信息失败：" + e.getMessage());
        }
    }

    @Override
    public ResponseResult dynamicDeviceForm(JSONObject jsonObject) {
        log.info("dynamicDeviceForm原始参数：" + jsonObject);
        try {
            /**
             * 1、参数校验
             */
            String sbzlx = jsonObject.getString(SysConstant.FIELD_SBZLX);

            String oid = jsonObject.getString(SysConstant.FIELD_OID);
            String gdtype = jsonObject.getString(SysConstant.FIELD_GDTYPE);
            String versionid = jsonObject.getString(SysConstant.FIELD_VERSIONID);
            String sbid = jsonObject.getString(SysConstant.FIELD_SBID);
            if (StrUtil.isEmpty(sbzlx) || StrUtil.isEmpty(oid) || StrUtil.isEmpty(sbid)
                    || StrUtil.isEmpty(gdtype) || StrUtil.isEmpty(versionid)) {
                throw new BizException("入参sbid/sbzlx/oid/gdtype/versionid不为空");
            }

            //本库查找不全数据但有坐标 getDeviceInfo接口参数的设备子类型key为modelid，需要做转换
            jsonObject.put(SysConstant.FIELD_MODELID, sbzlx);
            ResponseResult<JSONObject> deviceResult = this.getDeviceInfo(jsonObject);
            if (!deviceResult.isSuccess()) {
                throw new BizException("查无该设备的信息");
            }
            JSONObject deviceOld = deviceResult.getData();
            //通过代理获取设备信息(无坐标)
            JSONObject device = dataBrokerUtil.getInfo(oid, sbzlx);
            if (device != null) {
                // 坐标处理
                List<Point> points1 = new ArrayList<>();
                if (deviceOld.get(SysConstant.FIELD_POINTS) != null && deviceOld.get("geotype") != null) {//坐标
                    JSONArray points = deviceOld.getJSONArray(SysConstant.FIELD_POINTS);
                    for (int j = 0; j < points.size(); j++) {
//                        Point point = JSONObject.parseObject(points.getString(j), Point.class);//取到的类型就是Point.class,重复解析会报错
                        Point point = JSON.toJavaObject(points.getJSONObject(j), Point.class);
                        points1.add(point);
                    }
                }
                String shape = shapeUtil.dealAddDeviceShape(points1, deviceOld.getString("geotype"), null);
                device.put(SysConstant.FIELD_SHAPE, shape);
                device.put("geotype", deviceOld.get("geotype"));
                device.put(SysConstant.FIELD_POINTS, deviceOld.get("points"));
            } else {
                device = deviceOld;
            }

            /**
             * 2、判断设备字段
             */
            Map<String, Object> modelType = tyDao.getModelNameByType(null, sbzlx);
            if (modelType == null) {
                throw new BizException("设备信息有误或不存该类设备！");
            }
            String modelName = MapUtil.getStr(modelType, "modelname");
            if (StrUtil.isEmpty(modelName)) {
                throw new BizException("设备子类型[" + sbzlx + "]模型：缺失modelname字段");
            }
//            String txTableName = SysConstant.pre_table_tx+modelName;
//            String zyTableName = SysConstant.pre_table_zy+modelName;
//            String sbTableName=tyDao.getTableNameByModelName(txTableName.toUpperCase()).toLowerCase();//大写查找
//            //取表字段名称
//            if(sbTableName!= null){
//                List<Map> fieldList =tyDao.getFieldFormTablename(sbTableName+(sbTableName.contains(SysConstant.pre_table_sb)?"":"_ver"));
//            }
            //需要获取Name的字段，并且需要下拉查询，特殊字段下拉框
//            List<String> specSelectField = Arrays.asList(ParamSet.fieldsToSearchName);
            List<JSONObject> fieldList = tyDao.getTxFieldByClassid(modelType.get("classid").toString(), sbzlx);//该对象所有字段
            //添加必填字段
            fieldList.addAll(ParamSet.getfieldsLocalMustbe());

//            对设备字段处理(动态表单处理)
            List<Map<String, Object>> resultData = new ArrayList<>();//返回的对象
            for (Map field : fieldList) {

                //3.1 构建输入框信息-基础字段
                Map newField = new HashMap<>();
                String fieldname = field.get("fieldname").toString();
                newField.put("fieldName", fieldname);//字段名称
                newField.put("fieldAlias", field.get("fieldalias"));//字段注解
                newField.put("isRequired", false);//是否必填
                newField.put("isVisible", true);//是否可见
                newField.put("isEditable", true);//是否可编辑
                newField.put("isSearch", false);//不去搜索下拉
                Object fieldValue = device.get(fieldname);
                if (fieldValue == null || StrUtil.isEmpty(fieldValue.toString())) {
                    newField.put("fieldValue", "");//字段值
                } else {
                    newField.put("fieldValue", fieldValue);//字段值
                }

                // 3.2 获取基础下拉字段数据源（名称，编码，例如：水泥杆-1，木杆-2）
                Object codeexpress = field.get("codeexpress");
                if (codeexpress != null && StrUtil.isNotEmpty(codeexpress.toString())) {
                    String sql = codeexpress.toString();
                    if (StrUtil.equals(sql, SysConstant.SQL_WHERE) || !sql.contains("=")) {
                        newField.put("optional", "");
                    } else {
                        QueryWrapper queryWrapper = new QueryWrapper();
                        queryWrapper.apply(sql);
                        List<JSONObject> fieldValues = tyDao.getFieldValueBySql(queryWrapper);
                        newField.put("optional", fieldValues);
                        newField.put("isSearch", true);
                    }
                } else {
                    newField.put("optional", "");
                }

                //3.3 特殊获取下拉字段数据源（下拉为空时）
                if (StrUtil.isEmpty(newField.get("optional").toString()) && ArrayUtil.contains(ParamSet.fieldsToSearchName, fieldname)) {
                    //变压器特殊处理了，其他设备走公用方法
                /*    if(sbzlx== bianyaqi 并且 有ssxl，ssgt 字段){

                    }else {*/
                    JSONObject tqParam = new JSONObject();
                    tqParam.put("versionid", versionid);
                    tqParam.put("gdtype", gdtype);
                    tqParam.put("customSql", " AND t.classid in (" + ParamSet.field2Classids.get(fieldname) + ")");//拼接设备的classid
                    List<JSONObject> optionalList = this.getDeviceTqList(tqParam);//下发数据中找对应字段的值
                    List<Map> optionals = new ArrayList<>();
                    for (Map optional : optionalList) {
                        Map<String, Object> map1 = new HashMap<>();
                        map1.put("oid", optional.get("oid"));
                        map1.put("sbid", optional.get("sbid"));
                        map1.put("codename", optional.get("sbmc"));
                        optionals.add(map1);
                    }
                    newField.put("optional", optionals);
                    newField.put("isSearch", true);
//                    }
                }

                // 3.4 默认设备的可见、可编辑、是否可为空 设置字段
                if (ArrayUtil.contains(ParamSet.MODELID_BYQ_ALL, sbzlx)) {
                    if (ArrayUtil.contains(ParamSet.getCustomFieldsBysbzlx.get("BYQ"), fieldname)) { //fielname -> sbmc
                        newField.put("isRequired", true);//是否必填
                        newField.put("isVisible", true);//是否可见
                        newField.put("isEditable", true);//是否可编辑
                    } else {
                        newField.put("isRequired", false);//是否必填
                        newField.put("isVisible", false);//是否可见
                        newField.put("isEditable", false);//是否可编辑
                    }
                } else if (ArrayUtil.contains(ParamSet.MODELID_GT_ALL, sbzlx)) {
                    if (ArrayUtil.contains(ParamSet.getCustomFieldsBysbzlx.get("GT"), fieldname)) {
                        newField.put("isRequired", true);//是否必填
                        newField.put("isVisible", true);//是否可见
                        newField.put("isEditable", true);//是否可编辑
                    } else {
                        newField.put("isRequired", false);//是否必填
                        newField.put("isVisible", false);//是否可见
                        newField.put("isEditable", false);//是否可编辑
                    }
                } else if (ArrayUtil.contains(ParamSet.MODELID_ZF_ALL, sbzlx)) {
                    if (ArrayUtil.contains(ParamSet.getCustomFieldsBysbzlx.get("ZF"), fieldname)) {
                        newField.put("isRequired", true);//是否必填
                        newField.put("isVisible", true);//是否可见
                        newField.put("isEditable", true);//是否可编辑
                    } else {
                        newField.put("isRequired", false);//是否必填
                        newField.put("isVisible", false);//是否可见
                        newField.put("isEditable", false);//是否可编辑
                    }
                } else if (ArrayUtil.contains(ParamSet.MODELID_DL_ALL, sbzlx)) {
                    if (ArrayUtil.contains(ParamSet.getCustomFieldsBysbzlx.get("DL"), fieldname)) {
                        newField.put("isRequired", true);//是否必填
                        newField.put("isVisible", true);//是否可见
                        newField.put("isEditable", true);//是否可编辑
                    } else {
                        newField.put("isRequired", false);//是否必填
                        newField.put("isVisible", false);//是否可见
                        newField.put("isEditable", false);//是否可编辑
                    }
                } else if (ArrayUtil.contains(ParamSet.MODELID_ZNSB_ALL, sbzlx)) {
                    if (ArrayUtil.contains(ParamSet.getCustomFieldsBysbzlx.get("ZNSB"), fieldname)) {
                        newField.put("isRequired", true);//是否必填
                        newField.put("isVisible", true);//是否可见
                        newField.put("isEditable", true);//是否可编辑
                    } else {
                        newField.put("isRequired", false);//是否必填
                        newField.put("isVisible", false);//是否可见
                        newField.put("isEditable", false);//是否可编辑
                    }
                }

                resultData.add(newField);
            }
            log.info("dynamicDeviceForm最终返回：" + JSONObject.toJSONString(resultData));
            return ResponseResult.success(resultData);
        } catch (Exception e) {
            return ResponseResult.failed("获取动态表单失败：" + e.getMessage());
        }
    }

    @Override
    public ResponseResult<JSONObject> getStatisticsForTask(JSONObject jsonObject) {
        log.info("原始参数:" + jsonObject.toJSONString());

        //参数校验
        String gdtype = jsonObject.getString("gdtype");
       /* String gdoid=jsonObject.getString("gdoid");
        String tqsbid=jsonObject.getString("tqsbid");
        if(StrUtil.isEmpty(jsonObject.getString("gdoid")) || StrUtil.isEmpty(jsonObject.getString("tqsbid"))){
            return ResponseResult.failed(jsonObject,"参数错误!(例如:gdoid/tqsbid)");
        }
*/
        Map<String, Object> param = new HashMap<>();
        //工单类型：1为专线，台区为2
        if (StrUtil.isNotEmpty(gdtype)) {
            param.put(SysConstant.FIELD_GDTYPE, gdtype);
            String userid = jsonObject.getString(SysConstant.FIELD_USER_ID);
            //用户
            if (gdtype.equals(SysConstant.TASK_STATE_TQ) || gdtype.equals(SysConstant.TASK_STATE_ZX)) {
                if (StrUtil.isNotEmpty(userid)) {
                    param.put(SysConstant.FIELD_USER_ID, userid);
                }
            }
            //单位编号
            if (gdtype.equals(SysConstant.TASK_STATE_HIGH_CHECK)) {
                String orgNo = jsonObject.getString("orgNo");
                if (StrUtil.isNotEmpty(orgNo)) {
                    param.put("orgno", orgNo.substring(0, 7));
                }
            }
        }
        // 2.1已办
        List<Integer> sftsParam = ListUtil.list(false, SysConstant.SFTS_PUSH_WEB, SysConstant.SFTS_AUDIT_SUCCESS);
        param.put("sftsList", sftsParam);
        param.put("isdone", SysConstant.IS_DONE_TRUE);
        int done = deviceDao.getTaskListCount(param);

        // 2.2 代办
        List<Integer> sftsParam1 = ListUtil.list(false, SysConstant.SFTS_ISSUE);
        param.put("sftsList", sftsParam1);
        param.put("isdone", SysConstant.IS_DONE_FALSE);
        int doing = deviceDao.getTaskListCount(param);

        JSONObject result = new JSONObject();
        result.put("done", done);
        result.put("doing", doing);

        return ResponseResult.success(result);
    }

    /**
     * 特殊字段处理(图形到台账)
     */
    private static void specialFieldValidation(JSONObject jsonObject) {
        if (jsonObject.get("sbmc") != null && StrUtil.isNotEmpty(jsonObject.getString("sbmc"))) {
            jsonObject.put("yxbh", jsonObject.get("sbmc"));
            jsonObject.put("xlmc", jsonObject.get("sbmc"));
            jsonObject.put("gtbh", jsonObject.get("sbmc"));
            jsonObject.put("bdzmc", jsonObject.get("sbmc"));
        }
        if (jsonObject.get("sbmc") != null && StrUtil.isNotEmpty(jsonObject.getString("sbmc"))) {
            jsonObject.put("gtbh", jsonObject.get("sbmc"));
        }
        if (jsonObject.get("yxdw") != null && StrUtil.isNotEmpty(jsonObject.getString("yxdw"))) {
            jsonObject.put("ywdw", jsonObject.get("yxdw"));
        }
        if (jsonObject.get("ssds") != null && StrUtil.isNotEmpty(jsonObject.getString("ssds"))) {
            jsonObject.put("zcdw", jsonObject.get("ssds"));
        }
        jsonObject.put("tzly", "2");//台账来源（1:pc端,2:app）
    }
}
